#!/usr/bin/env bash
# ssh-rotate: SSH login keys that replace themselves.   https://www.sshrotate.com
# Copyright (c) 2026 Klajdi Gashi. Free to use; see https://www.sshrotate.com/license.txt
#
# Servers trust one certificate authority (CA) public key, once. This tool then makes a
# new login key at a set interval and signs it with the CA, so no login key on disk
# is useful for longer than one rotation period. The CA key itself stays in hardware
# where the machine has it (Secure Enclave, FIDO security key) or in an ssh-agent.
set -euo pipefail
umask 077
shopt -u patsub_replacement 2>/dev/null || true

VERSION=0.7.2
# Where new versions come from. The second address is the same site under its hosting name.
SOURCE_URLS="${SSH_ROTATE_SOURCE:-https://www.sshrotate.com https://sshrotate.pages.dev}"
ROOT="${SSH_ROTATE_HOME:-$HOME/.ssh/rotating}"
SSH_CONFIG="${SSH_ROTATE_SSH_CONFIG:-$HOME/.ssh/config}"
OS=$(uname -s)
# Windows means Git Bash here (Git for Windows), which is what the script runs under there.
case "$OS" in MINGW*|MSYS*|CYGWIN*) WINDOWS=yes ;; *) WINDOWS=no ;; esac
ME="${USER:-$(id -un)}"
SE_PROVIDER=/usr/lib/ssh-keychain.dylib

# Defaults; 'setup' writes them to $ROOT/config, 'set' changes them.
CA_BACKEND=""        # secure-enclave | fido | password | agent | file
CA_LABEL="ssh-user-ca" # name of the Secure Enclave identity
PRINCIPAL="$ME-admin"
ROTATE_MINUTES=""    # how often the login key is replaced; 'set every 30m' changes it
ROTATE_HOURS=24      # the same, as older configurations wrote it
OVERLAP_MINUTES=60   # how long the outgoing certificate stays valid after a rotation, at most one period
CA_TOUCH_ID=no       # secure-enclave only: yes = Touch ID for every signature (one tap per rotation)
ALLOWED_FROM=""      # comma-separated source addresses servers accept certificates from; empty = anywhere
CERT_OPTIONS="permit-pty permit-port-forwarding"
GITHUB_SYNC=no       # only read: where version 0.2.0 recorded that GitHub sync was on
GITHUB_GH=gh
# shellcheck disable=SC1091
[ -f "$ROOT/config" ] && . "$ROOT/config"

[ -n "$ROTATE_MINUTES" ] || ROTATE_MINUTES=$((ROTATE_HOURS * 60))
SELF="$ROOT/bin/ssh-rotate"
CA_KEY="$ROOT/ca/ca"
CA_PUB="$ROOT/ca/ca.pub"
CUR="$ROOT/current"
HOSTS="$ROOT/hosts"
LOCK="$ROOT/.lock"
LOG="$ROOT/rotate.log"
GIT_HOSTS="$ROOT/git-hosts"
RECOVERY_PUB="$ROOT/recovery.pub"
BG_LABEL=local.ssh-rotate
TAB=$(printf '\t')
HTTP_LIMIT=20
H_NAME="" H_KIND="" H_API="" H_EXTRA=""
CONNECT=(-o ConnectTimeout=20)

# Installs made before backends existed always used the Secure Enclave.
[ -n "$CA_BACKEND" ] || { [ -f "$CA_PUB" ] && CA_BACKEND=secure-enclave; } || true

die()  { echo "ssh-rotate: $*" >&2; exit 1; }
die_code() { local code=$1; shift; echo "ssh-rotate: $*" >&2; exit "$code"; }
note() { echo "ssh-rotate: $*" >&2; }
log()  { mkdir -p "$ROOT"; echo "$(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG"; }
have() { command -v "$1" >/dev/null 2>&1; }
# contains <text> <part>. Used instead of 'cmd | grep -q', which fails under pipefail
# when grep stops reading before the command has finished writing.
contains() { case "$1" in *"$2"*) return 0 ;; esac; return 1; }

short_host() { hostname -s 2>/dev/null || uname -n | cut -d. -f1; }
mtime()      { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; }
fingerprint() { ssh-keygen -lf "$1" | awk '{print $2}'; }
need_setup() { [ -f "$CA_PUB" ] || die "not set up yet: run 'ssh-rotate setup'"; }

# A password question has to reach a person: on the terminal when there is one, otherwise
# through whatever SSH_ASKPASS program is configured (a desktop dialog).
has_tty() { [ -z "${SSH_ROTATE_NO_TTY:-}" ] && { : </dev/tty; } 2>/dev/null; }
keygen_ask() { if has_tty; then ssh-keygen "$@" </dev/tty; else ssh-keygen "$@" </dev/null; fi; }
# True when the private key file is protected by a password.
encrypted() { ! ssh-keygen -y -P "" -f "$1" </dev/null >/dev/null 2>&1; }

ssh_() {
  if [ -n "${SSH_ROTATE_SSH_CONFIG:-}" ]; then ssh -F "$SSH_CONFIG" "$@"; else ssh "$@"; fi
}

# "major minor" of the local OpenSSH client.
ssh_version() { ssh -V 2>&1 | sed -n 's/^OpenSSH[^0-9]*\([0-9]*\)\.\([0-9]*\).*/\1 \2/p' | head -n1; }
version_at_least() {  # version_at_least "<major> <minor>" <major> <minor>
  # shellcheck disable=SC2086
  set -- $1 "$2" "$3"
  [ "$#" -eq 4 ] || return 1
  [ "$1" -gt "$3" ] || { [ "$1" -eq "$3" ] && [ "$2" -ge "$4" ]; }
}
# The option was called PubkeyAcceptedKeyTypes before OpenSSH 8.5.
algo_keyword() {
  if version_at_least "$(ssh_version)" 8 5; then echo PubkeyAcceptedAlgorithms; else echo PubkeyAcceptedKeyTypes; fi
}

# Runs a command with a time limit when the system has a way to enforce one.
limited() {
  local secs=$1; shift
  if have timeout; then timeout "$secs" "$@"
  elif have gtimeout; then gtimeout "$secs" "$@"
  elif have perl; then perl -e 'alarm shift; exec @ARGV or exit 127' "$secs" "$@"
  else "$@"; fi
}

set_config() {
  local key=$1 value=$2
  mkdir -p "$ROOT"; touch "$ROOT/config"
  grep -v "^$key=" "$ROOT/config" > "$ROOT/config.new" || true
  printf '%s="%s"\n' "$key" "$value" >> "$ROOT/config.new"
  mv -f "$ROOT/config.new" "$ROOT/config"
  eval "$key=\$value"
}

# "30m", "45min", "1h", "12h" or "2d" as a number of minutes.
parse_period() {
  local n unit
  case "$1" in
    *min) n=${1%min}; unit=m ;;
    *[mhd]) n=${1%?}; unit=${1#"$n"} ;;
    *) return 1 ;;
  esac
  case "$n" in ''|*[!0-9]*) return 1 ;; esac
  case "$unit" in m) echo "$n" ;; h) echo $((n * 60)) ;; d) echo $((n * 1440)) ;; esac
}

# A number of minutes the way a person writes it: 30m, 6h, 1h 30m.
period_words() {
  if [ $(($1 % 60)) -eq 0 ]; then echo "$(($1 / 60))h"
  elif [ "$1" -lt 60 ]; then echo "${1}m"
  else echo "$(($1 / 60))h $(($1 % 60))m"; fi
}

# The background check runs more often when keys are replaced more often than hourly.
bg_seconds() { if [ "$ROTATE_MINUTES" -lt 60 ]; then echo 300; else echo 1800; fi; }

check_settings() {
  case "$PRINCIPAL" in ''|*[!A-Za-z0-9._@-]*) die "principal may only contain letters, digits and . _ @ -" ;; esac
  case "$ALLOWED_FROM" in *[!A-Za-z0-9.:,*?!/_-]*) die "allowed-from is a comma-separated list of addresses, CIDR ranges or host patterns" ;; esac
  case "$ROTATE_MINUTES" in ''|*[!0-9]*) die "the rotation period must be a whole number" ;; esac
  [ "$ROTATE_MINUTES" -ge 10 ] || die "the shortest rotation period is 10 minutes"
  [ "$ROTATE_MINUTES" -le 43200 ] || die "the longest rotation period is 30 days"
  case "$OVERLAP_MINUTES" in ''|*[!0-9]*) die "overlap must be a number of minutes" ;; esac
  case "$CERT_OPTIONS" in *[!a-z0-9\ -]*) die "cert-options is a space-separated list such as: permit-pty permit-port-forwarding" ;; esac
}

# True when a rotation can happen with nobody at the keyboard.
unattended() {
  case "$CA_BACKEND" in
    file) return 0 ;;
    secure-enclave) [ "$CA_TOUCH_ID" != yes ] ;;
    *) return 1 ;;
  esac
}

backend_name() {
  case "$CA_BACKEND" in
    secure-enclave) echo "Secure Enclave (label $CA_LABEL, Touch ID per rotation: $CA_TOUCH_ID)" ;;
    fido)  echo "FIDO security key (touch per rotation)" ;;
    password) echo "encrypted key file (password per rotation)" ;;
    agent) echo "ssh-agent" ;;
    file)  echo "key file on disk, no hardware protection" ;;
    *)     echo "none" ;;
  esac
}

ca_line() {
  need_setup
  local from=""
  [ -z "$ALLOWED_FROM" ] || from="from=\"$ALLOWED_FROM\","
  printf 'cert-authority,%sprincipals="%s" %s %s\n' \
    "$from" "$PRINCIPAL" "$(awk '{print $1, $2}' "$CA_PUB")" "ssh-rotate-ca@$(short_host)"
}

# ---------------------------------------------------------------------------
# Rotation
# ---------------------------------------------------------------------------

acquire_lock() {
  local tries=0
  mkdir -p "$ROOT"
  until mkdir "$LOCK" 2>/dev/null; do
    # A lock older than three minutes belongs to a run that died (a Touch ID prompt can hold it).
    if [ $(( $(date +%s) - $(mtime "$LOCK") )) -gt 180 ]; then
      rmdir "$LOCK" 2>/dev/null || true
      continue
    fi
    tries=$((tries + 1))
    [ "$tries" -lt 600 ] || die "another rotation is holding $LOCK"
    sleep 0.2
  done
  trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT
}

is_fresh() {
  local now created expires
  [ -s "$CUR/id_ed25519" ] && [ -s "$CUR/id_ed25519-cert.pub" ] || return 1
  [ -r "$CUR/created" ] && [ -r "$CUR/expires" ] || return 1
  now=$(date +%s); created=$(<"$CUR/created"); expires=$(<"$CUR/expires")
  [ "$now" -ge $((created - 300)) ] || return 1               # clock moved backwards
  [ $((now - created)) -lt $((ROTATE_MINUTES * 60)) ] || return 1
  [ $((expires - now)) -gt 120 ] || return 1
}

prune() {
  # Delete every generation that is not current and whose certificate has expired.
  local now cur g
  now=$(date +%s); cur=$(current_name)
  for g in "$ROOT"/gen/*/; do
    [ -d "$g" ] || continue
    g=${g%/}
    [ "${g##*/}" = "$cur" ] && continue
    if [ ! -r "$g/expires" ] || [ "$(<"$g/expires")" -le "$now" ]; then rm -rf "$g"; fi
  done
}

# The name of the generation that is current.
current_name() {
  if [ -L "$CUR" ]; then basename "$(readlink "$CUR")"
  elif [ -r "$CUR/name" ]; then cat "$CUR/name"; fi
}

# Makes a generation the current one.
set_current() {
  if [ "$WINDOWS" = no ]; then swap_link "gen/$1" "$CUR"; return 0; fi
  # Git Bash has no dependable symlinks, so 'current' is a folder swapped in by renaming.
  rm -rf "$CUR.new" "$CUR.old"
  mkdir "$CUR.new"
  cp "$ROOT/gen/$1"/* "$CUR.new/"
  echo "$1" > "$CUR.new/name"
  [ ! -e "$CUR" ] || mv "$CUR" "$CUR.old"
  mv "$CUR.new" "$CUR"
  rm -rf "$CUR.old"
}

# A path as it must be written into the ssh config. On Windows both Git's ssh and
# Windows' own ssh read that file, and both understand C:/short/names without spaces.
winpath() {
  if [ "$WINDOWS" = yes ]; then cygpath -ms "$1" 2>/dev/null || cygpath -m "$1"
  else printf '%s\n' "$1"; fi
}

# Points the symlink $2 at $1 in one step, so a concurrent ssh never sees a mismatched key and cert.
swap_link() {
  rm -f "$2.new"
  ln -s "$1" "$2.new"
  mv -fT "$2.new" "$2" 2>/dev/null || mv -fh "$2.new" "$2" 2>/dev/null || {
    rm -f "$2.new"; ln -sfn "$1" "$2"
  }
}

sign_key() {  # sign_key <key.pub> <key id> <serial> <validity>
  local pub=$1 opt
  local args=(-q -I "$2" -n "$PRINCIPAL" -z "$3" -V "$4" -O clear)
  for opt in $CERT_OPTIONS; do args+=(-O "$opt"); done
  case "$CA_BACKEND" in
    secure-enclave)
      SSH_SK_PROVIDER="$SE_PROVIDER" ssh-keygen -s "$CA_KEY" "${args[@]}" "$pub" </dev/null ;;
    fido)  ssh-keygen -s "$CA_KEY" "${args[@]}" "$pub" </dev/null ;;
    password) keygen_ask -s "$CA_KEY" "${args[@]}" "$pub" ;;
    agent) ssh-keygen -U -s "$CA_PUB" "${args[@]}" "$pub" </dev/null ;;
    file)  ssh-keygen -s "$CA_KEY" "${args[@]}" "$pub" </dev/null ;;
    *) echo "unknown CA_BACKEND '$CA_BACKEND'" >&2; return 1 ;;
  esac
}

rotate_locked() {
  local now name d valid_m err
  need_setup
  now=$(date +%s)
  name=$(date +%Y%m%dT%H%M%S)
  d="$ROOT/gen/$name"
  mkdir -p "$ROOT/gen"
  mkdir "$d" 2>/dev/null || { d="$d.$$"; name="$name.$$"; mkdir "$d"; }
  # The old certificate outlives a rotation by the overlap, but never by more than one period.
  valid_m=$OVERLAP_MINUTES
  [ "$valid_m" -le "$ROTATE_MINUTES" ] || valid_m=$ROTATE_MINUTES
  valid_m=$((ROTATE_MINUTES + valid_m))

  ssh-keygen -q -t ed25519 -N "" -C "rotating-$name" -f "$d/id_ed25519"
  case "$CA_BACKEND" in
    secure-enclave) [ "$CA_TOUCH_ID" != yes ] || note "confirm with Touch ID to sign a new login key" ;;
    fido) note "touch your security key to sign a new login key" ;;
    password) note "your ssh-rotate password is needed to sign a new login key" ;;
  esac
  if ! sign_key "$d/id_ed25519.pub" "$ME@$(short_host)/$name" "$now" "-5m:+${valid_m}m" 2>"$d/sign.err" ||
     [ ! -s "$d/id_ed25519-cert.pub" ]; then
    err=$(cat "$d/sign.err" 2>/dev/null || true)
    rm -rf "$d"
    log "FAILED signing: $err"
    case "$CA_BACKEND" in
      secure-enclave) die "the Secure Enclave CA did not sign the new key (Touch ID cancelled or timed out?): $err" ;;
      fido)  die "the security key did not sign the new key (not plugged in, or not touched in time?): $err" ;;
      agent) die "the ssh-agent did not sign the new key (is the CA key loaded? try: ssh-add -l): $err" ;;
      password) die "the new key was not signed (wrong password, or nowhere to ask for it?): $err" ;;
      *)     die "could not sign the new key: $err" ;;
    esac
  fi
  rm -f "$d/sign.err"
  echo "$now" > "$d/created"
  echo $((now + valid_m * 60)) > "$d/expires"

  set_current "$name"
  prune
  log "rotated -> $name ($(fingerprint "$d/id_ed25519.pub"))"
  git_sync_all 10
}

cmd_rotate() { acquire_lock; rotate_locked; }

cmd_ensure() {
  if ! is_fresh; then
    acquire_lock
    is_fresh || rotate_locked
  fi
  # 'ensure git <name>' is what ssh runs for a Git host: finish an upload that failed earlier.
  local name=""
  case "${1:-}" in git) name=${2:-} ;; github) name=github ;; esac
  if [ -n "$name" ] && [ -e "$ROOT/pending/$name" ]; then
    githost_sync "$name" 20 || die "could not install the current key on $name"
  fi
}

# Shows a desktop notice, where the system has a way to.
notify() {
  if [ -n "${SSH_ROTATE_NOTIFY_LOG:-}" ]; then echo "$1" >> "$SSH_ROTATE_NOTIFY_LOG"
  elif [ "$OS" = Darwin ] && have osascript; then
    osascript -e "display notification \"$1\" with title \"SSH Rotate\"" >/dev/null 2>&1 || true
  elif have notify-send; then
    notify-send "SSH Rotate" "$1" >/dev/null 2>&1 || true
  fi
}

# The background check: runs every half hour and looks whether the login key is due.
cmd_background() {
  local stamp state
  case "${1:-}" in
    on)
      need_setup
      default_home || die "the background check belongs to the default installation in ~/.ssh/rotating"
      bg_install
      if state=$(bg_state); then echo "Background check is on ($state)."
      else die "the background check could not be started on this system"; fi
      return 0 ;;
    off)
      bg_remove
      echo "Background check is off. Keys are still replaced when you connect."
      return 0 ;;
  esac
  [ -f "$CA_PUB" ] || return 0
  prune
  ! is_fresh || return 0
  if unattended; then cmd_ensure; return 0; fi
  # The key is due and making one takes a person. Ask once per key, with a notice that says
  # why. If that is ignored the next connection asks again, not this check every half hour.
  stamp=$(cat "$CUR/created" 2>/dev/null || echo none)
  [ "$(cat "$ROOT/.asked" 2>/dev/null || true)" != "$stamp" ] || return 0
  echo "$stamp" > "$ROOT/.asked"
  case "$CA_BACKEND" in
    secure-enclave)
      notify "Your SSH login key is due. Confirm with Touch ID to make the new one."
      cmd_ensure ;;
    fido)
      notify "Your SSH login key is due. Touch your security key to make the new one."
      cmd_ensure ;;
    *)
      # A password cannot be asked for from the background.
      notify "Your SSH login key is due. Run 'ssh-rotate rotate', or connect to a server, to make the new one." ;;
  esac
}

# ---------------------------------------------------------------------------
# Local ssh configuration
# ---------------------------------------------------------------------------

write_ssh_config() {
  local list="" algo name ssh run=$SELF cur=$CUR root
  [ -s "$HOSTS" ] && list=$(sed 's/^.*@//' "$HOSTS" | awk 'NF && !seen[$0]++' | paste -sd, -)
  algo=$(algo_keyword)
  if [ "$WINDOWS" = yes ]; then
    # Windows' own ssh cannot start a shell script, so the command names Git's bash as well.
    root=$(winpath "$ROOT"); root=${root%/}
    run="$(winpath /)"; run="${run%/}/bin/bash.exe $root/bin/ssh-rotate"
    cur="$root/current"
    # shellcheck disable=SC2088   # the tilde is meant for ssh to expand, not this shell
    case "$ROOT" in "$HOME"/*) cur="~/${ROOT#"$HOME"/}/current" ;; esac
  fi
  {
    echo "# Generated by ssh-rotate; edits are overwritten. Change hosts with 'ssh-rotate add|remove <host>'."
    if [ -n "$list" ]; then
      echo "Match originalhost $list exec \"$run ensure\""
      echo "    IdentityFile $cur/id_ed25519"
      echo "    IdentitiesOnly yes"
      # Offer only the certificate. If 'ensure' fails this whole block is skipped,
      # so ssh falls back to whatever static keys the host still lists.
      echo "    $algo ssh-ed25519-cert-v01@openssh.com"
    fi
    # Git hosts take the bare key, so no certificate-only restriction here.
    git_hosts | while IFS="$TAB" read -r name _ _ ssh _; do
      echo "Match originalhost $ssh exec \"$run ensure git $name\""
      echo "    IdentityFile $cur/id_ed25519"
      echo "    IdentitiesOnly yes"
    done
  } > "$ROOT/ssh_config.new"
  mv -f "$ROOT/ssh_config.new" "$ROOT/ssh_config"
}

include_line() {
  local root
  root=$(winpath "$ROOT"); root=${root%/}
  # Git's ssh takes an Include path as absolute only when it starts with "/", Windows' ssh.exe
  # only when it starts with a drive letter. "~/..." is the one form both accept.
  if [ "$WINDOWS" = yes ]; then
    # shellcheck disable=SC2088   # the tilde is meant for ssh to expand, not this shell
    case "$ROOT" in "$HOME"/*) root="~/${ROOT#"$HOME"/}" ;; esac
  fi
  case "$root" in
    *[[:space:]]*) echo "Include \"$root/ssh_config\"" ;;
    *) echo "Include $root/ssh_config" ;;
  esac
}

# The Include must sit above every Host block so the rotating key is offered first.
hook_ssh_config() {
  local inc; inc=$(include_line)
  mkdir -p "$(dirname "$SSH_CONFIG")"
  [ -e "$SSH_CONFIG" ] || { : > "$SSH_CONFIG"; chmod 600 "$SSH_CONFIG"; }
  if [ "$(grep -v '^[[:space:]]*\(#.*\)\{0,1\}$' "$SSH_CONFIG" | head -n1)" = "$inc" ]; then return 0; fi
  if [ ! -w "$SSH_CONFIG" ]; then
    note "$SSH_CONFIG is read-only; add this as its first line yourself:"
    note "  $inc"
    return 0
  fi
  cp -p "$SSH_CONFIG" "$SSH_CONFIG.before-ssh-rotate"
  { echo "$inc"; grep -vxF "$inc" "$SSH_CONFIG.before-ssh-rotate" || true; } > "$ROOT/.ssh_config.tmp"
  cat "$ROOT/.ssh_config.tmp" > "$SSH_CONFIG"    # keeps the file's mode and any symlink
  rm -f "$ROOT/.ssh_config.tmp"
}

unhook_ssh_config() {
  local inc; inc=$(include_line)
  [ -f "$SSH_CONFIG" ] && grep -qxF "$inc" "$SSH_CONFIG" || return 0
  grep -vxF "$inc" "$SSH_CONFIG" > "$ROOT/.ssh_config.tmp" || true
  cat "$ROOT/.ssh_config.tmp" > "$SSH_CONFIG"
  rm -f "$ROOT/.ssh_config.tmp"
}

add_host() {
  touch "$HOSTS"
  grep -qxF "$1" "$HOSTS" || echo "$1" >> "$HOSTS"
  write_ssh_config
}

# Removes the exact entry; a bare host name also removes every user@host entry for it.
remove_host() {
  [ -f "$HOSTS" ] || return 0
  awk -v t="$1" '$0 == t { next } index(t, "@") == 0 && substr($0, length($0) - length(t)) == "@" t { next } { print }' \
    "$HOSTS" > "$HOSTS.new"
  mv -f "$HOSTS.new" "$HOSTS"
  write_ssh_config
}

# ---------------------------------------------------------------------------
# Background job: rotates when that needs nobody present, otherwise deletes expired keys.
# ---------------------------------------------------------------------------

default_home() { [ "$ROOT" = "$HOME/.ssh/rotating" ]; }
bg_plist() { echo "$HOME/Library/LaunchAgents/$BG_LABEL.plist"; }
bg_unit_dir() { echo "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"; }

bg_install() {
  # The job cannot carry a custom SSH_ROTATE_HOME, and there is one job per user.
  default_home || { note "custom SSH_ROTATE_HOME: no background job installed"; return 0; }
  # On Windows there is none: keys rotate when you connect, and expired ones are deleted then.
  [ "$WINDOWS" = no ] || return 0
  case "$OS" in
    Darwin)
      mkdir -p "$HOME/Library/LaunchAgents"
      cat > "$(bg_plist)" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$BG_LABEL</string>
  <key>ProgramArguments</key>
  <array><string>$SELF</string><string>background</string></array>
  <key>StartInterval</key><integer>$(bg_seconds)</integer>
  <key>RunAtLoad</key><true/>
  <key>StandardErrorPath</key><string>$ROOT/launchd.err</string>
</dict>
</plist>
EOF
      chmod 644 "$(bg_plist)"
      launchctl bootout "gui/$(id -u)/$BG_LABEL" 2>/dev/null || true
      launchctl bootstrap "gui/$(id -u)" "$(bg_plist)" 2>/dev/null ||
        note "could not load the launchd job; keys still rotate when you ssh"
      ;;
    *)
      if have systemctl && systemctl --user show-environment >/dev/null 2>&1; then
        mkdir -p "$(bg_unit_dir)"
        cat > "$(bg_unit_dir)/ssh-rotate.service" <<EOF
[Unit]
Description=ssh-rotate: rotate or clean up SSH login keys

[Service]
Type=oneshot
ExecStart=$SELF background
EOF
        cat > "$(bg_unit_dir)/ssh-rotate.timer" <<EOF
[Unit]
Description=ssh-rotate timer

[Timer]
OnBootSec=2min
OnUnitActiveSec=$(( $(bg_seconds) / 60 ))min

[Install]
WantedBy=timers.target
EOF
        systemctl --user daemon-reload
        systemctl --user enable --now ssh-rotate.timer >/dev/null 2>&1 ||
          note "could not start the systemd timer; keys still rotate when you ssh"
      elif have crontab; then
        { crontab -l 2>/dev/null | grep -vF "ssh-rotate background" || true
          echo "*/$(( $(bg_seconds) / 60 )) * * * * $SELF background >/dev/null 2>&1"; } | crontab -
      else
        note "no systemd user session or cron found; keys still rotate when you ssh"
      fi
      ;;
  esac
}

bg_remove() {
  default_home || return 0
  [ "$WINDOWS" = no ] || return 0
  case "$OS" in
    Darwin)
      launchctl bootout "gui/$(id -u)/$BG_LABEL" 2>/dev/null || true
      rm -f "$(bg_plist)" ;;
    *)
      if [ -f "$(bg_unit_dir)/ssh-rotate.timer" ]; then
        systemctl --user disable --now ssh-rotate.timer >/dev/null 2>&1 || true
        rm -f "$(bg_unit_dir)/ssh-rotate.timer" "$(bg_unit_dir)/ssh-rotate.service"
        systemctl --user daemon-reload 2>/dev/null || true
      fi
      if have crontab && contains "$(crontab -l 2>/dev/null || true)" "ssh-rotate background"; then
        crontab -l 2>/dev/null | grep -vF "ssh-rotate background" | crontab - || true
      fi ;;
  esac
}

bg_state() {
  default_home || return 1
  [ "$WINDOWS" = no ] || return 1
  case "$OS" in
    Darwin)
      if launchctl print "gui/$(id -u)/$BG_LABEL" >/dev/null 2>&1; then echo "launchd job loaded"; else return 1; fi ;;
    *)
      if have systemctl && systemctl --user is-active ssh-rotate.timer >/dev/null 2>&1; then echo "systemd user timer active"
      elif have crontab && contains "$(crontab -l 2>/dev/null || true)" "ssh-rotate background"; then echo "cron entry installed"
      else return 1; fi ;;
  esac
}

# Makes 'ssh-rotate' a command by linking it into a directory that is already on PATH.
# Where Windows keeps per-user commands that PowerShell and cmd find by name.
windows_apps() { [ -n "${LOCALAPPDATA:-}" ] && cygpath -u "$LOCALAPPDATA/Microsoft/WindowsApps" 2>/dev/null; }

link_into_path() {
  local dir bash
  default_home || return 0
  if [ "$WINDOWS" = yes ]; then
    # Symlinks are copies here and would go stale, so the command is a small launcher:
    # one for Git Bash, one for PowerShell and cmd.
    mkdir -p "$HOME/bin"
    printf '#!/bin/sh\nexec bash "%s" "$@"\n' "$SELF" > "$HOME/bin/ssh-rotate"
    chmod +x "$HOME/bin/ssh-rotate"
    if dir=$(windows_apps) && [ -d "$dir" ]; then
      bash="$(cygpath -w /)"; bash="${bash%\\}\\bin\\bash.exe"
      printf '@"%s" "%s" %%*\r\n' "$bash" "$(cygpath -w "$SELF")" > "$dir/ssh-rotate.cmd"
    fi
    case ":$PATH:" in *":$HOME/bin:"*) ;; *) note "open a new Git Bash window to use the 'ssh-rotate' command" ;; esac
    return 0
  fi
  for dir in "$HOME/.local/bin" "$HOME/bin" /opt/homebrew/bin /usr/local/bin; do
    case ":$PATH:" in *":$dir:"*) ;; *) continue ;; esac
    [ -d "$dir" ] && [ -w "$dir" ] || continue
    ln -sf "$SELF" "$dir/ssh-rotate"
    return 0
  done
  mkdir -p "$HOME/.local/bin"
  ln -sf "$SELF" "$HOME/.local/bin/ssh-rotate"
  note "linked into ~/.local/bin, which is not on your PATH; add it, or call $SELF"
}

# ---------------------------------------------------------------------------
# Setup
# ---------------------------------------------------------------------------

secure_enclave_available() {
  [ "$OS" = Darwin ] && [ -e "$SE_PROVIDER" ] && have sc_auth &&
    contains "$(sc_auth 2>&1 || true)" create-ctk-identity
}

se_identity_fp() {
  sc_auth list-ctk-identities -t ssh 2>/dev/null |
    awk -v l="$CA_LABEL" '$4 == l { print $2; found = 1 } END { exit !found }'
}

create_ca_secure_enclave() {
  local fp tmp pub prot=none n k answers
  secure_enclave_available ||
    die "this machine cannot keep SSH keys in a Secure Enclave (needs macOS 26 or newer on Apple silicon or a T2 Mac); use --backend fido, agent or file"
  if ! fp=$(se_identity_fp); then
    [ "$CA_TOUCH_ID" = yes ] && prot=bio
    sc_auth create-ctk-identity -l "$CA_LABEL" -k p-256-ne -t "$prot" -N "$CA_LABEL" ||
      die "could not create the Secure Enclave identity"
    fp=$(se_identity_fp) || die "Secure Enclave identity '$CA_LABEL' not found after creating it"
  fi
  # Every Secure Enclave identity exports to the same file name. With several
  # identities, keep the k-th by answering the overwrite prompts, and try each k.
  n=$(sc_auth list-ctk-identities -t ssh | awk 'NR > 1' | wc -l | tr -d ' ')
  k=1
  while [ "$k" -le "$n" ] && [ ! -f "$CA_KEY" ]; do
    tmp=$(mktemp -d "$ROOT/.export.XXXXXX")
    answers=$(awk -v k="$k" -v n="$n" 'BEGIN { print ""; for (i = 2; i <= n; i++) print (i <= k ? "y" : "n") }')
    (cd "$tmp" && printf '%s\n' "$answers" |
      SSH_SK_PROVIDER="$SE_PROVIDER" ssh-keygen -q -K -N "" >/dev/null 2>&1) || true
    pub="$tmp/id_ecdsa_sk_rk.pub"
    if [ -f "$pub" ] && [ "$(fingerprint "$pub")" = "$fp" ]; then
      mv "${pub%.pub}" "$CA_KEY"; mv "$pub" "$CA_PUB"
    fi
    rm -rf "$tmp"
    k=$((k + 1))
  done
  [ -f "$CA_KEY" ] || die "could not export the handle for identity $fp from the Secure Enclave"
}

create_ca() {
  local given_pub=$1
  case "$CA_BACKEND" in
    secure-enclave) create_ca_secure_enclave ;;
    fido)
      note "touch your security key when it blinks (it may ask for its PIN first)"
      ssh-keygen -q -t ed25519-sk -O application=ssh:ssh-rotate-ca -N "" -C ssh-rotate-ca -f "$CA_KEY" ||
        ssh-keygen -q -t ecdsa-sk -O application=ssh:ssh-rotate-ca -N "" -C ssh-rotate-ca -f "$CA_KEY" ||
        die "could not create a CA key on the security key"
      ;;
    agent)
      if [ -n "$given_pub" ]; then
        [ -f "$given_pub" ] || die "$given_pub: no such file"
        awk '{print $1, $2}' "$given_pub" > "$CA_PUB"
      else
        note "choose a passphrase for the new CA key; it is asked for when the key is loaded into your ssh-agent"
        ssh-keygen -q -t ed25519 -C ssh-rotate-ca -f "$CA_KEY" || die "could not create the CA key"
        ssh-add "$CA_KEY" || die "could not load the CA key into your ssh-agent (is one running?)"
      fi
      contains "$(ssh-add -L 2>/dev/null || true)" "$(awk '{print $2}' "$CA_PUB")" ||
        { rm -f "$CA_PUB"; die "that CA key is not loaded in your ssh-agent; ssh-add it and run setup again"; }
      ;;
    password)
      note "choose a password. You type it once per rotation (every $(period_words "$ROTATE_MINUTES")) to sign the new login key."
      keygen_ask -q -t ed25519 -C ssh-rotate-ca -f "$CA_KEY" || { rm -f "$CA_KEY" "$CA_PUB"; die "could not create the CA key"; }
      if ! encrypted "$CA_KEY"; then
        rm -f "$CA_KEY" "$CA_PUB"
        die "an empty password protects nothing. Run setup again and choose one (it needs a terminal to ask on), or pass --backend file if you really want none"
      fi
      ;;
    file)
      ssh-keygen -q -t ed25519 -N "" -C ssh-rotate-ca -f "$CA_KEY"
      ;;
    *) die "unknown backend '$CA_BACKEND' (use secure-enclave, fido, password, agent or file)" ;;
  esac
}

cmd_setup() {
  local backend="" touch_id="" hours="" every="" from="" principal="" ca_pub="" background=yes link=yes hook=yes
  while [ $# -gt 0 ]; do
    case "$1" in
      --backend) backend=${2:?--backend needs a value}; shift ;;
      --touch-id) touch_id=yes ;;
      --hours) hours=${2:?--hours needs a value}; shift ;;
      --every) every=${2:?--every needs a period such as 30m or 1h}; shift ;;
      --from) from=${2:?--from needs a value}; shift ;;
      --principal) principal=${2:?--principal needs a value}; shift ;;
      --ca-pub) ca_pub=${2:?--ca-pub needs a file}; shift ;;
      --no-background) background=no ;;
      --no-link) link=no ;;
      --no-hook) hook=no ;;
      *) die "setup: unknown option '$1'" ;;
    esac
    shift
  done
  version_at_least "$(ssh_version)" 8 2 || die "OpenSSH 8.2 or newer is required on this machine (found: $(ssh -V 2>&1))"

  mkdir -p "$ROOT/ca" "$ROOT/gen" "$ROOT/bin"
  # Running from a checkout or a download: keep a copy where ssh and the background job expect it.
  if [ ! "${BASH_SOURCE[0]}" -ef "$SELF" ]; then
    cp "${BASH_SOURCE[0]}" "$SELF.new"; chmod 700 "$SELF.new"; mv -f "$SELF.new" "$SELF"
  fi

  if [ -f "$CA_PUB" ]; then
    [ -z "$backend$touch_id$ca_pub" ] ||
      die "a CA already exists here ($(backend_name)); its backend cannot be changed. Other settings: 'ssh-rotate set'"
  else
    if [ -n "$backend" ]; then CA_BACKEND=$backend
    elif secure_enclave_available; then CA_BACKEND=secure-enclave
    else CA_BACKEND="password"; fi
    [ -z "$touch_id" ] || CA_TOUCH_ID=yes
    [ "$CA_TOUCH_ID" != yes ] || [ "$CA_BACKEND" = secure-enclave ] || die "--touch-id only applies to the secure-enclave backend"
    # A Touch ID identity is a different Secure Enclave key, so it gets its own label.
    [ "$CA_TOUCH_ID" != yes ] || [ "$CA_LABEL" != ssh-user-ca ] || CA_LABEL="ssh-user-ca-touch"
  fi
  if [ -n "$hours" ]; then
    case "$hours" in ''|*[!0-9]*) die "--hours takes a whole number; for shorter periods use --every 30m" ;; esac
    ROTATE_MINUTES=$((hours * 60))
  fi
  if [ -n "$every" ]; then ROTATE_MINUTES=$(parse_period "$every") || die "--every takes a period such as 30m, 1h, 12h or 2d"; fi
  [ -z "$from" ] || ALLOWED_FROM=$from
  [ -z "$principal" ] || PRINCIPAL=$principal
  check_settings
  # Version 0.2.0 kept GitHub's switch in the config file; it now lives with the other Git hosts.
  if [ "$GITHUB_SYNC" = yes ]; then
    host_save github github - github.com,gist.github.com,ssh.github.com "$GITHUB_GH"
    GITHUB_SYNC=no
  fi

  cat > "$ROOT/config" <<EOF
# ssh-rotate settings (shell syntax). Change them with 'ssh-rotate set'.
CA_BACKEND="$CA_BACKEND"
CA_LABEL="$CA_LABEL"
PRINCIPAL="$PRINCIPAL"
ROTATE_MINUTES="$ROTATE_MINUTES"
OVERLAP_MINUTES="$OVERLAP_MINUTES"
CA_TOUCH_ID="$CA_TOUCH_ID"
ALLOWED_FROM="$ALLOWED_FROM"
CERT_OPTIONS="$CERT_OPTIONS"
EOF

  if [ ! -f "$CA_PUB" ]; then
    create_ca "$ca_pub"
    log "created CA $(fingerprint "$CA_PUB") ($CA_BACKEND)"
  fi
  write_ssh_config
  [ "$hook" = no ] || hook_ssh_config
  [ "$background" = no ] || bg_install
  [ "$link" = no ] || link_into_path
  cmd_ensure

  echo "ssh-rotate is set up. CA: $(fingerprint "$CA_PUB") ($(backend_name))"
  if [ "$CA_BACKEND" = file ]; then
    echo "Note: the CA key is an unprotected file ($CA_KEY). Login keys still expire every"
    echo "$(period_words "$ROTATE_MINUTES"), but anyone who can read that file can sign their own. A password"
    echo "(--backend password) or a security key (--backend fido) closes that."
  fi
  echo "Next: ssh-rotate add user@your-server"
}

cmd_set() {
  [ $# -eq 2 ] || die "usage: ssh-rotate set <every|overlap|allowed-from|principal|cert-options> <value>"
  need_setup
  case "$1" in
    every)        ROTATE_MINUTES=$(parse_period "$2") || die "say how often with a unit: 30m, 1h, 12h or 2d" ;;
    hours)        case "$2" in ''|*[!0-9]*) die "hours must be a whole number; for shorter periods: ssh-rotate set every 30m" ;; esac
                  ROTATE_MINUTES=$(($2 * 60)) ;;
    overlap)      OVERLAP_MINUTES=$2 ;;
    allowed-from) [ "$2" != any ] || set -- "$1" ""; ALLOWED_FROM=$2 ;;
    principal)    PRINCIPAL=$2 ;;
    cert-options) CERT_OPTIONS=$2 ;;
    *) die "unknown setting '$1'" ;;
  esac
  check_settings
  case "$1" in
    every|hours)
      set_config ROTATE_MINUTES "$ROTATE_MINUTES"
      # The background check keeps pace with a shorter period.
      if bg_state >/dev/null; then bg_install; fi
      echo "Login keys are now replaced every $(period_words "$ROTATE_MINUTES")."
      unattended || [ "$ROTATE_MINUTES" -ge 240 ] ||
        echo "Each new key needs you (Touch ID, password or security key), so expect to be asked that often." ;;
    overlap)
      set_config OVERLAP_MINUTES "$2" ;;
    allowed-from)
      set_config ALLOWED_FROM "$2"
      echo "Servers learn the new address list when you run: ssh-rotate sync" ;;
    principal)
      set_config PRINCIPAL "$2"
      echo "Run 'ssh-rotate sync': it makes a login key with the new principal and updates every server." ;;
    cert-options)
      set_config CERT_OPTIONS "$2"
      echo "Applies from the next rotation ('ssh-rotate rotate' to do it now)." ;;
  esac
}

cmd_uninstall() {
  bg_remove
  unhook_ssh_config
  local dir
  for dir in "$HOME/.local/bin" "$HOME/bin" /opt/homebrew/bin /usr/local/bin; do
    [ -L "$dir/ssh-rotate" ] && [ "$(readlink "$dir/ssh-rotate")" = "$SELF" ] && rm -f "$dir/ssh-rotate"
  done
  if [ "$WINDOWS" = yes ] && default_home; then
    rm -f "$HOME/bin/ssh-rotate"
    if dir=$(windows_apps); then rm -f "$dir/ssh-rotate.cmd"; fi
  fi
  echo "Removed the ssh config hook, the background job and the command link."
  echo "Your servers still trust the CA: run 'ssh-rotate remove <host>' for each one first if you want that gone."
  [ -z "$(git_hosts)" ] || echo "Git hosts still hold your last key and their tokens are still stored: run '<host kind> disable' for $(git_hosts | cut -f1 | paste -sd' ' -)."
  echo "Keys and settings are still in $ROOT; delete that folder to finish."
  if [ "$CA_BACKEND" = secure-enclave ]; then
    echo "The Secure Enclave key stays until you delete it: sc_auth list-ctk-identities, then sc_auth delete-ctk-identity -h <hash>"
  fi
}

cmd_upgrade() {
  have curl || die "curl is required to upgrade"
  local url got=no
  for url in $SOURCE_URLS; do
    if curl -fsSL "$url/ssh-rotate" -o "$SELF.new" 2>/dev/null; then got=yes; break; fi
  done
  [ "$got" = yes ] || { rm -f "$SELF.new"; die "download failed"; }
  bash -n "$SELF.new" || { rm -f "$SELF.new"; die "the downloaded file is not a valid script"; }
  chmod 700 "$SELF.new"; mv -f "$SELF.new" "$SELF"
  "$SELF" version
}

# ---------------------------------------------------------------------------
# Servers
# ---------------------------------------------------------------------------

# Remote steps are written twice: POSIX sh for everything Unix-like, PowerShell for Windows.

sh_enroll() { cat <<'EOF'
set -eu
umask 077
# Under Windows' own sshd this would be Git's sh, started by cmd.exe. The keys of a Windows
# account are not where this script would look, so it hands over to the PowerShell version.
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) if [ -n "${PROMPT:-}" ]; then echo WINDOWS; exit 3; fi ;; esac
v=$( (ssh -V || true; sshd -V || true; /usr/sbin/sshd -V || true) 2>&1 | sed -n 's/^OpenSSH[^0-9]*\([0-9]*\)\.\([0-9]*\).*/\1 \2/p' | head -n1)
set -- $v
if [ "$#" -eq 2 ]; then
  if [ "$1" -lt "$MIN_MAJOR" ] || { [ "$1" -eq "$MIN_MAJOR" ] && [ "$2" -lt "$MIN_MINOR" ]; }; then
    echo "UNSUPPORTED OpenSSH $1.$2 (this CA needs $MIN_MAJOR.$MIN_MINOR or newer)"; exit 0
  fi
fi
# The address this server sees the client coming from must be allowed, or the new line locks it out.
seen=${SSH_CLIENT:-}; seen=${seen%% *}
if [ -n "$ALLOWED" ] && [ -n "$seen" ]; then
  case "$ALLOWED" in
    *[!0-9.,]*) ;;   # ranges, patterns or IPv6: not checked here
    *) case ",$ALLOWED," in *",$seen,"*) ;; *) echo "WRONGADDR $seen"; exit 0 ;; esac ;;
  esac
fi
mkdir -p "$HOME/.ssh"
f="$HOME/.ssh/authorized_keys"
[ -e "$f" ] || : > "$f"
if grep -qxF "$CA_LINE" "$f"; then
  echo ALREADY
else
  cp -p "$f" "$f.before-ssh-rotate"
  result=ADDED
  if grep -qF "$CA_B64" "$f"; then
    grep -vF "$CA_B64" "$f" > "$f.tmp" || true
    cat "$f.tmp" > "$f"; rm -f "$f.tmp"
    result=UPDATED
  fi
  [ -z "$(tail -c1 "$f")" ] || echo >> "$f"
  printf '%s\n' "$CA_LINE" >> "$f"
  if command -v restorecon >/dev/null 2>&1; then restorecon -R "$HOME/.ssh" 2>/dev/null || true; fi
  echo "$result"
  if [ "$result" = UPDATED ]; then
    # A changed line is put back unless the client confirms that it can still log in.
    : > "$f.ssh-rotate-pending"
    F="$f" REVERT="$REVERT" nohup sh -c 'sleep "$REVERT"
      if [ -e "$F.ssh-rotate-pending" ]; then cat "$F.before-ssh-rotate" > "$F"; rm -f "$F.ssh-rotate-pending"; fi' \
      </dev/null >/dev/null 2>&1 &
    echo "NOTE pending"
  fi
fi
if [ -e /etc/NIXOS ]; then echo "NOTE nixos"; fi
EOF
}

ps_enroll() { cat <<'EOF'
$ErrorActionPreference = 'Stop'
$line = '__CA_LINE__'
$b64 = '__CA_B64__'
$allowed = '__ALLOWED__'
$seen = ("$env:SSH_CLIENT" -split ' ')[0]
if ($allowed -and $seen -and ($allowed -match '^[0-9.,]+$') -and (($allowed -split ',') -notcontains $seen)) { "WRONGADDR $seen"; exit 0 }
$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($admin) { $f = Join-Path $env:ProgramData 'ssh\administrators_authorized_keys' } else { $f = Join-Path $env:USERPROFILE '.ssh\authorized_keys' }
$dir = Split-Path $f
if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
$created = -not (Test-Path $f)
$old = @()
if (-not $created) { $old = @(Get-Content $f) }
if ($old -contains $line) { 'ALREADY'; exit 0 }
$result = 'ADDED'
if (-not $created) { Copy-Item $f "$f.before-ssh-rotate" -Force }
$keep = @($old | Where-Object { -not $_.Contains($b64) })
if ($keep.Count -ne $old.Count) { $result = 'UPDATED' }
Set-Content -Path $f -Value ($keep + $line) -Encoding ascii
if ($created -and $admin) { icacls.exe $f /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null }
$result
EOF
}

sh_remove() { cat <<'EOF'
set -eu
umask 077
# Under Windows' own sshd this would be Git's sh, started by cmd.exe. The keys of a Windows
# account are not where this script would look, so it hands over to the PowerShell version.
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) if [ -n "${PROMPT:-}" ]; then echo WINDOWS; exit 3; fi ;; esac
f="$HOME/.ssh/authorized_keys"
n=0
if [ "$GUARD" = 1 ] && [ -f "$f" ]; then
  left=$(grep -vF "$KEYS" "$f" | grep -c '^[[:space:]]*[^#[:space:]]' || true)
  if [ "$left" -eq 0 ]; then echo LASTKEY; exit 0; fi
fi
if [ -f "$f" ]; then
  cp -p "$f" "$f.$SUFFIX"
  for k in $KEYS; do
    if grep -qF "$k" "$f"; then
      grep -vF "$k" "$f" > "$f.tmp" || true
      cat "$f.tmp" > "$f"; rm -f "$f.tmp"
      n=$((n + 1))
    fi
  done
fi
echo "REMOVED $n"
EOF
}

ps_remove() { cat <<'EOF'
$ErrorActionPreference = 'Stop'
$keys = '__KEYS__'.Split(' ', [StringSplitOptions]::RemoveEmptyEntries)
$files = @((Join-Path $env:ProgramData 'ssh\administrators_authorized_keys'), (Join-Path $env:USERPROFILE '.ssh\authorized_keys'))
$n = 0
if ('__GUARD__' -eq '1') {
  $left = 0
  foreach ($f in $files) {
    try { if (Test-Path $f) { $left += @(Get-Content $f | Where-Object { $l = $_; $l.Trim() -and -not $l.Trim().StartsWith('#') -and -not ($keys | Where-Object { $l.Contains($_) }) }).Count } } catch { }
  }
  if ($left -eq 0) { 'LASTKEY'; exit 0 }
}
foreach ($f in $files) {
  try {
    if (-not (Test-Path $f)) { continue }
    $old = @(Get-Content $f)
    $keep = @($old | Where-Object { $l = $_; -not ($keys | Where-Object { $l.Contains($_) }) })
    if ($keep.Count -ne $old.Count) {
      Copy-Item $f "$f.__SUFFIX__" -Force
      Set-Content -Path $f -Value $keep -Encoding ascii
      $n += $old.Count - $keep.Count
    }
  } catch { }
}
"REMOVED $n"
EOF
}

# PowerShell takes a whole script as base64 of UTF-16LE, which survives any remote shell.
ps_encode() {
  if have iconv; then printf '%s' "$1" | iconv -f UTF-8 -t UTF-16LE | base64 | tr -d '\n'
  elif have perl; then printf '%s' "$1" | perl -0777 -pe 's/(.)/$1\0/gs' | base64 | tr -d '\n'
  else die "iconv or perl is needed to talk to a Windows server"; fi
}

# remote_run <target> <env assignments> <sh script> <powershell script>
# Tries the Unix script; if the far side is Windows, runs the PowerShell one instead.
# Prints the script's output. ssh's own error text is shown only when the step fails.
remote_run() {
  local target=$1 env=$2 sh_script=$3 ps_script=$4 out rc=0 err
  # Any credential may be used here, not only the certificate: a host that is already
  # enrolled for one account is certificate-only in the generated ssh config.
  local opts=("${CONNECT[@]}" -o IdentitiesOnly=no -o "$(algo_keyword)=+ssh-ed25519")
  err=$(mktemp "$ROOT/.err.XXXXXX")
  # The leading ':' is a no-op for a Unix shell. cmd.exe and PowerShell do not get past it,
  # so on a Windows server nothing runs here even when it has an sh.exe on its PATH.
  out=$(printf '%s\n' "$sh_script" | ssh_ "${opts[@]}" "$target" ": && env $env sh -s" 2>"$err") || rc=$?
  if [ "$rc" -ne 255 ] && { [ "$rc" -ne 0 ] || [ -z "$out" ] || [ "$out" = WINDOWS ]; }; then
    # cmd.exe expands the first word to Windows_NT, PowerShell the second, a Unix shell neither.
    # shellcheck disable=SC2016
    if contains "$(ssh_ "${opts[@]}" "$target" 'echo %OS% $env:OS' 2>/dev/null </dev/null || true)" Windows_NT; then
      rc=0
      out=$(ssh_ "${opts[@]}" "$target" \
        "powershell -NoProfile -NonInteractive -EncodedCommand $(ps_encode "$ps_script")" 2>"$err" </dev/null) || rc=$?
      out=$(printf '%s' "$out" | tr -d '\r')
    fi
  fi
  [ "$rc" -eq 0 ] || cat "$err" >&2
  rm -f "$err"
  printf '%s\n' "$out"
  return "$rc"
}

verify_cert_login() {
  ssh_ -o BatchMode=yes "${CONNECT[@]}" -o IdentitiesOnly=yes -i "$CUR/id_ed25519" \
    -o "$(algo_keyword)=ssh-ed25519-cert-v01@openssh.com" "$1" exit >/dev/null 2>&1
}

# Hosts to act on: the arguments, or every enrolled host.
targets() {
  if [ $# -gt 0 ]; then printf '%s\n' "$@"
  elif [ -s "$HOSTS" ]; then cat "$HOSTS"; fi
}

cmd_add() {
  [ $# -ge 1 ] || die "usage: ssh-rotate add <[user@]host> [<[user@]host>...]"
  need_setup
  cmd_ensure
  local target line b64 out result min ps rc=0 revert=${SSH_ROTATE_REVERT_SECONDS:-120}
  line=$(ca_line); b64=$(awk '{print $2}' "$CA_PUB")
  case "$CA_BACKEND" in secure-enclave|fido) min="MIN_MAJOR=8 MIN_MINOR=2" ;; *) min="MIN_MAJOR=6 MIN_MINOR=5" ;; esac
  ps=$(ps_enroll); ps=${ps//__CA_LINE__/$line}; ps=${ps//__CA_B64__/$b64}; ps=${ps//__ALLOWED__/$ALLOWED_FROM}
  for target; do
    out=$(remote_run "$target" "CA_LINE='$line' CA_B64='$b64' ALLOWED='$ALLOWED_FROM' REVERT=$revert $min" "$(sh_enroll)" "$ps") ||
      { echo "$target: could not connect, or could not edit authorized_keys there" >&2; rc=1; continue; }
    result=$(printf '%s\n' "$out" | head -n1)
    case "$result" in
      ADDED|UPDATED|ALREADY) ;;
      WRONGADDR*)
        echo "$target: sees you coming from ${result#WRONGADDR }, which is not in allowed-from ($ALLOWED_FROM); nothing was changed" >&2
        echo "  fix it with: ssh-rotate set allowed-from <addresses>   (or 'any')" >&2
        rc=1; continue ;;
      *) echo "$target: ${result:-no answer from the server}" >&2; rc=1; continue ;;
    esac
    if verify_cert_login "$target"; then
      case "$out" in *"NOTE pending"*)
        # shellcheck disable=SC2016
        ssh_ -o BatchMode=yes "${CONNECT[@]}" -o IdentitiesOnly=yes -i "$CUR/id_ed25519" "$target" \
          'rm -f "$HOME/.ssh/authorized_keys.ssh-rotate-pending"' </dev/null ||
          { echo "$target: could not confirm the change; the server puts the previous line back within ${revert}s" >&2; rc=1; continue; } ;;
      esac
      add_host "$target"
      case "$result" in
        ADDED)   echo "$target: now trusts your CA; certificate login verified" ;;
        UPDATED) echo "$target: CA line updated; certificate login verified" ;;
        ALREADY) echo "$target: already trusted your CA; certificate login verified" ;;
      esac
      log "added $target"
      [ ! -f "$RECOVERY_PUB" ] || recovery_install "$target" </dev/null || true
      case "$out" in *"NOTE nixos"*)
        echo "  NixOS: this works now and survives rebuilds, but to keep it in your configuration use 'ssh-rotate snippet nixos'" ;;
      esac
    else
      case "$out" in
        *"NOTE pending"*)
          echo "$target: certificate login FAILED with the changed line; the server puts the previous line back within ${revert}s" >&2 ;;
        *)
          echo "$target: the CA line is in place but certificate login FAILED, so ssh keeps using your old key for it" >&2 ;;
      esac
      [ -z "$ALLOWED_FROM" ] ||
        echo "  certificates are only accepted from $ALLOWED_FROM; is that the address this server sees you coming from?" >&2
      rc=1
    fi
  done
  return $rc
}

cmd_remove() {
  local guard=1
  [ "${1:-}" != --force ] || { guard=0; shift; }
  [ $# -ge 1 ] || die "usage: ssh-rotate remove [--force] <[user@]host> [<[user@]host>...]"
  need_setup
  local target b64 ps out rc=0
  b64=$(awk '{print $2}' "$CA_PUB")
  ps=$(ps_remove); ps=${ps//__KEYS__/$b64}; ps=${ps//__SUFFIX__/before-ssh-rotate-remove}; ps=${ps//__GUARD__/$guard}
  for target; do
    if out=$(remote_run "$target" "KEYS='$b64' SUFFIX=before-ssh-rotate-remove GUARD=$guard" "$(sh_remove)" "$ps"); then
      if [ "$out" = LASTKEY ]; then
        echo "$target: the CA is the only key left for that account, so removing it would lock you out; nothing was changed" >&2
        echo "  if you have another way in (or that is the point), repeat with: ssh-rotate remove --force $target" >&2
        rc=1; continue
      fi
      remove_host "$target"
      echo "$target: CA trust removed from authorized_keys (a line declared elsewhere, such as NixOS configuration, is not touched)"
      log "removed $target"
    else
      echo "$target: could not connect; CA trust NOT removed. 'ssh-rotate forget $target' only stops using the rotating key here." >&2
      rc=1
    fi
  done
  return $rc
}

cmd_forget() {
  [ $# -ge 1 ] || die "usage: ssh-rotate forget <[user@]host> [<[user@]host>...]"
  local target
  for target; do remove_host "$target"; echo "$target: no longer uses the rotating key (the server was not changed)"; done
}

cmd_retire() {
  [ $# -ge 2 ] || die "usage: ssh-rotate retire <[user@]host> <old-key.pub> [<old-key.pub>...]"
  need_setup
  local target=$1 pub b64 list="" ps out; shift
  for pub; do
    [ -f "$pub" ] || die "$pub: no such file"
    b64=$(awk '{print $2}' "$pub")
    [ -n "$b64" ] || die "$pub: not a public key file"
    [ "$b64" != "$(awk '{print $2}' "$CA_PUB")" ] || die "$pub is the CA key; refusing"
    list="$list $b64"
  done
  list=${list# }
  cmd_ensure
  verify_cert_login "$target" ||
    die "$target: certificate-only login does not work, so no static key was removed"
  ps=$(ps_remove); ps=${ps//__KEYS__/$list}; ps=${ps//__SUFFIX__/before-ssh-rotate-retire}; ps=${ps//__GUARD__/0}
  out=$(remote_run "$target" "KEYS='$list' SUFFIX=before-ssh-rotate-retire GUARD=0" "$(sh_remove)" "$ps") ||
    die "$target: could not edit authorized_keys"
  if verify_cert_login "$target"; then
    echo "$target: ${out#REMOVED } static key(s) removed, certificate login still works"
    log "retired static keys on $target"
  else
    die "$target: certificate login failed after the edit; restore authorized_keys.before-ssh-rotate-retire through your open session or console"
  fi
}

cmd_test() {
  need_setup
  cmd_ensure
  local target rc=0 any=no
  while IFS= read -r target; do
    [ -n "$target" ] || continue
    any=yes
    if verify_cert_login "$target" </dev/null; then echo "ok      $target"
    else echo "FAILED  $target"; rc=1; fi
  done <<EOF
$(targets "$@")
EOF
  [ "$any" = yes ] || echo "no hosts yet: ssh-rotate add user@your-server"
  return $rc
}

cmd_list() {
  if [ -s "$HOSTS" ]; then cat "$HOSTS"; else echo "no hosts yet: ssh-rotate add user@your-server" >&2; fi
}

cert_has_principal() {
  ssh-keygen -Lf "$CUR/id_ed25519-cert.pub" 2>/dev/null |
    awk -v p="$PRINCIPAL" '/Principals:/ { f = 1; next } /Critical Options:/ { f = 0 } f && $1 == p { ok = 1 } END { exit !ok }'
}

# Pushes the current CA line to every enrolled host, after 'set allowed-from' or 'set principal'.
cmd_sync() {
  need_setup
  [ -s "$HOSTS" ] || { echo "no hosts yet"; return 0; }
  if ! cert_has_principal; then
    acquire_lock; rotate_locked
    rmdir "$LOCK" 2>/dev/null || true
  fi
  local list=()
  while IFS= read -r t; do [ -z "$t" ] || list+=("$t"); done < "$HOSTS"
  cmd_add "${list[@]}"
}

# ---------------------------------------------------------------------------
# Snippets: the same trust, written for other ways of configuring a server
# ---------------------------------------------------------------------------

cmd_snippet() {
  need_setup
  local kind=${1:-} user=${2:-root} line ca from=""
  line=$(ca_line); ca=$(awk '{print $1, $2}' "$CA_PUB")
  [ -z "$ALLOWED_FROM" ] || from="from=\"$ALLOWED_FROM\" "
  case "$kind" in
    line) echo "$line" ;;
    shell)
      echo "# Paste into a shell on the server, logged in as the account you want to reach:"
      printf '%s\n' "mkdir -p ~/.ssh && chmod 700 ~/.ssh && printf '%s\\n' '$line' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
      ;;
    nixos)
      cat <<EOF
# NixOS: add to the configuration of the host, then rebuild.
users.users.$user.openssh.authorizedKeys.keys = [
  ''$line''
];
EOF
      ;;
    cloud-init)
      cat <<EOF
#cloud-config
# User data for a new server: account '$user' accepts your rotating certificates from first boot.
users:
  - name: $user
    ssh_authorized_keys:
      - '$line'
EOF
      ;;
    ansible)
      cat <<EOF
# Ansible task (needs the ansible.posix collection).
- name: Trust the ssh-rotate certificate authority
  ansible.posix.authorized_key:
    user: $user
    key: '$ca ssh-rotate-ca@$(short_host)'
    key_options: '${line%% *}'
EOF
      ;;
    sshd)
      cat <<EOF
#!/bin/sh
# Whole-server trust instead of a line per account. Run as root on the server.
# Afterwards these accounts accept your rotating certificates: $user
# (pass more names to 'ssh-rotate snippet sshd' separated by commas, e.g. root,deploy)
set -eu
umask 022
mkdir -p /etc/ssh/auth_principals
printf '%s\n' '$ca' > /etc/ssh/ssh-rotate-ca.pub
for account in $(echo "$user" | tr ',' ' '); do
  printf '%s\n' '$from$PRINCIPAL' > "/etc/ssh/auth_principals/\$account"
done
conf=/etc/ssh/sshd_config.d/50-ssh-rotate.conf
if [ -d /etc/ssh/sshd_config.d ] && grep -qi '^[[:space:]]*Include[[:space:]].*sshd_config\.d' /etc/ssh/sshd_config; then :; else conf=/etc/ssh/sshd_config; fi
if ! grep -qs 'ssh-rotate-ca.pub' "\$conf"; then
  [ "\$conf" != /etc/ssh/sshd_config ] || cp -p "\$conf" "\$conf.before-ssh-rotate"
  printf '%s\n' 'TrustedUserCAKeys /etc/ssh/ssh-rotate-ca.pub' 'AuthorizedPrincipalsFile /etc/ssh/auth_principals/%u' >> "\$conf"
fi
sshd=\$(command -v sshd || echo /usr/sbin/sshd)
"\$sshd" -t
systemctl reload sshd 2>/dev/null || systemctl reload ssh 2>/dev/null || service sshd reload 2>/dev/null || service ssh reload 2>/dev/null ||
  echo "sshd configuration is valid; reload sshd yourself to apply it"
EOF
      ;;
    windows)
      cat <<EOF
# Windows server with OpenSSH: run in an elevated PowerShell.
# Administrator accounts read this file; for a standard account use \$env:USERPROFILE\\.ssh\\authorized_keys instead.
\$f = "\$env:ProgramData\\ssh\\administrators_authorized_keys"
Add-Content -Path \$f -Encoding ascii -Value '$line'
icacls.exe \$f /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F'
EOF
      ;;
    *) die "usage: ssh-rotate snippet <line|shell|nixos|cloud-init|ansible|sshd|windows> [account]" ;;
  esac
}

# ---------------------------------------------------------------------------
# Git hosts. A hosted Git service accepts only the exact keys listed on your account
# (certificates are for Enterprise plans or self-hosted servers), so for these each new
# login key is uploaded through the service's API and the previous one deleted.
# ---------------------------------------------------------------------------

key_title_prefix() { echo "ssh-rotate:$(short_host | tr -cd 'A-Za-z0-9._-'):"; }
utc_date() { date -u -d "@$1" "+$2" 2>/dev/null || date -u -r "$1" "+$2"; }

# Enabled hosts, one per line: name, kind, API address, ssh host names, extra ("-" when unused).
git_hosts() {
  [ ! -s "$GIT_HOSTS" ] || cat "$GIT_HOSTS"
  # Version 0.2.0 kept GitHub's switch in the config file.
  if [ "$GITHUB_SYNC" = yes ] && ! grep -q "^github$TAB" "$GIT_HOSTS" 2>/dev/null; then
    printf 'github\tgithub\t-\tgithub.com,gist.github.com,ssh.github.com\t%s\n' "$GITHUB_GH"
  fi
}

host_load() {
  local line
  line=$(git_hosts | awk -F'\t' -v n="$1" '$1 == n && !seen { print; seen = 1 }')
  [ -n "$line" ] || return 1
  IFS="$TAB" read -r H_NAME H_KIND H_API _ H_EXTRA <<EOF
$line
EOF
}

host_save() {  # host_save <name> <kind> <api> <ssh hosts> <extra>
  mkdir -p "$ROOT"; touch "$GIT_HOSTS"
  awk -F'\t' -v n="$1" '$1 != n' "$GIT_HOSTS" > "$GIT_HOSTS.new"
  printf '%s\t%s\t%s\t%s\t%s\n' "$@" >> "$GIT_HOSTS.new"
  mv -f "$GIT_HOSTS.new" "$GIT_HOSTS"
}

host_forget() {
  [ -f "$GIT_HOSTS" ] || return 0
  awk -F'\t' -v n="$1" '$1 != n' "$GIT_HOSTS" > "$GIT_HOSTS.new"
  mv -f "$GIT_HOSTS.new" "$GIT_HOSTS"
}

# Access tokens live in the system keychain where there is one, otherwise in a private file.
token_file() { echo "$ROOT/tokens/$1"; }

token_get() {
  if [ -r "$(token_file "$1")" ]; then cat "$(token_file "$1")"
  elif [ "$OS" = Darwin ] && have security; then security find-generic-password -a "$ME" -s "ssh-rotate:$1" -w 2>/dev/null
  elif have secret-tool; then secret-tool lookup service ssh-rotate account "$1" 2>/dev/null
  else return 1; fi
}

token_del() {
  rm -f "$(token_file "$1")"
  if [ "$OS" = Darwin ] && have security; then
    security delete-generic-password -a "$ME" -s "ssh-rotate:$1" >/dev/null 2>&1 || true
  elif have secret-tool; then
    secret-tool clear service ssh-rotate account "$1" 2>/dev/null || true
  fi
}

token_put() {  # token_put <name> <token>
  local name=$1 token=$2
  token_del "$name"
  if [ "${SSH_ROTATE_TOKEN_STORE:-}" != file ]; then
    if [ "$OS" = Darwin ] && have security; then
      # Through 'security -i', so the token never appears on a command line.
      printf 'add-generic-password -U -a "%s" -s "ssh-rotate:%s" -w "%s"\n' "$ME" "$name" "$token" |
        security -i >/dev/null 2>&1 || true
    elif have secret-tool; then
      printf '%s' "$token" | secret-tool store --label "ssh-rotate $name" service ssh-rotate account "$name" 2>/dev/null || true
    fi
    [ "$(token_get "$name" || true)" != "$token" ] || return 0
  fi
  mkdir -p "$ROOT/tokens"
  printf '%s\n' "$token" > "$(token_file "$name")"
  [ "${SSH_ROTATE_TOKEN_STORE:-}" = file ] ||
    note "no system keychain to use: the token is kept in $(token_file "$name"), readable only by you"
}

# Picks whatever can read JSON here: jq, python3 or perl.
json_tool() {
  local tool=${SSH_ROTATE_JSON:-}
  if [ -z "$tool" ]; then
    if have jq; then tool=jq
    elif have python3; then tool=python3
    elif have perl && perl -MJSON::PP -e 1 2>/dev/null; then tool=perl
    else echo "ssh-rotate: jq, python3 or perl is needed to read the server's answers" >&2; return 1; fi
  fi
  echo "$tool"
}

# Reads a list of SSH keys as GitLab, Forgejo, Gitea or Bitbucket return it and prints
# one key per line: id <tab> title <tab> key
keys_tsv() {
  local tool; tool=$(json_tool) || return 1
  case "$tool" in
    jq) jq -r '(if type == "object" then .values else . end)[] | [(.id // .uuid | tostring), (.title // .label // ""), .key] | @tsv' ;;
    python3) python3 -c '
import json, sys
data = json.load(sys.stdin)
if isinstance(data, dict): data = data["values"]
for k in data:
    print("%s\t%s\t%s" % (k.get("id", k.get("uuid")), k.get("title", k.get("label")) or "", k["key"]))' ;;
    perl) perl -MJSON::PP -e '
local $/; my $d = decode_json(<STDIN>);
$d = $d->{values} if ref $d eq "HASH";
for my $k (@$d) { printf "%s\t%s\t%s\n", $k->{id} // $k->{uuid}, $k->{title} // $k->{label} // "", $k->{key} }' ;;
    *) echo "ssh-rotate: unknown JSON tool: $tool" >&2; return 1 ;;
  esac
}

json_field() {  # json_field <name>: one top-level string field of the JSON object on stdin
  local tool; tool=$(json_tool) || return 1
  case "$tool" in
    jq) jq -r --arg f "$1" '.[$f] // empty' ;;
    python3) python3 -c 'import json, sys; print(json.load(sys.stdin).get(sys.argv[1]) or "")' "$1" ;;
    perl) perl -MJSON::PP -e 'local $/; my $d = decode_json(<STDIN>); print(($d->{$ARGV[0]} // ""), "\n")' "$1" ;;
  esac
}

# host_http <method> <url> [json body]: prints the answer, fails unless the status is 2xx.
# The token goes to curl on standard input, so it is never visible in the process list.
host_http() {
  local method=$1 url=$2 body=${3:-} token auth out code
  local args=(-sS -g -K - --connect-timeout 8 --max-time "$HTTP_LIMIT" -X "$method" -H "Accept: application/json" -w '\n%{http_code}')
  [ -z "$body" ] || args+=(-H "Content-Type: application/json" --data "$body")
  token=$(token_get "$H_NAME" || true)
  [ -n "$token" ] || { echo "no access token is stored for $H_NAME" >&2; return 1; }
  case "$H_KIND" in
    gitlab)    auth="header = \"PRIVATE-TOKEN: $token\"" ;;
    bitbucket) auth="header = \"Authorization: Bearer $token\"" ;;
    *)         auth="header = \"Authorization: token $token\"" ;;
  esac
  out=$(printf '%s\n' "$auth" | curl "${args[@]}" "$url") || return 1
  code=${out##*$'\n'}; out=${out%$'\n'*}
  case "$code" in
    2??) printf '%s\n' "$out" ;;
    *) echo "HTTP $code $(printf '%s' "$out" | tr '\n' ' ' | cut -c1-200)" >&2; return 1 ;;
  esac
}

host_list() {
  case "$H_KIND" in
    github) limited "$HTTP_LIMIT" "$H_EXTRA" api user/keys --paginate --jq '.[] | [.id, .title, .key] | @tsv' ;;
    gitlab) host_http GET "$H_API/api/v4/user/keys?per_page=100" | keys_tsv ;;
    forgejo|gitea) host_http GET "$H_API/api/v1/user/keys?limit=50" | keys_tsv ;;
    bitbucket) host_http GET "$H_API/2.0/users/$H_EXTRA/ssh-keys?pagelen=100" | keys_tsv ;;
    *) return 1 ;;
  esac
}

# host_add <title> <key> <expiry>. Where the service can expire a key by itself it is told
# to, so a machine that stops rotating does not leave a working key behind.
host_add() {
  local title=$1 key=$2 expires=$3 body
  case "$H_KIND" in
    github) limited "$HTTP_LIMIT" "$H_EXTRA" api user/keys -f title="$title" -f key="$key" --silent ;;
    gitlab)
      body="\"title\":\"$title\",\"key\":\"$key\""
      # GitLab takes a date, and the key stops working at the start of that day (UTC).
      host_http POST "$H_API/api/v4/user/keys" "{$body,\"expires_at\":\"$(utc_date $((expires + 86400)) %Y-%m-%d)\"}" >/dev/null 2>&1 ||
        host_http POST "$H_API/api/v4/user/keys" "{$body}" >/dev/null ;;
    forgejo|gitea)
      host_http POST "$H_API/api/v1/user/keys" "{\"title\":\"$title\",\"key\":\"$key\"}" >/dev/null ;;
    bitbucket)
      body="{\"label\":\"$title\",\"key\":\"$key\"}"
      host_http POST "$H_API/2.0/users/$H_EXTRA/ssh-keys?expires_on=$(utc_date $((expires + 3600)) %Y-%m-%dT%H:%M:%SZ)" "$body" >/dev/null 2>&1 ||
        host_http POST "$H_API/2.0/users/$H_EXTRA/ssh-keys" "$body" >/dev/null ;;
    *) return 1 ;;
  esac
}

host_delete() {
  local id=$1
  case "$H_KIND" in
    github) limited "$HTTP_LIMIT" "$H_EXTRA" api -X DELETE "user/keys/$id" --silent ;;
    gitlab) host_http DELETE "$H_API/api/v4/user/keys/$id" >/dev/null ;;
    forgejo|gitea) host_http DELETE "$H_API/api/v1/user/keys/$id" >/dev/null ;;
    bitbucket) id=${id//\{/%7B}; id=${id//\}/%7D}
      host_http DELETE "$H_API/2.0/users/$H_EXTRA/ssh-keys/$id" >/dev/null ;;
    *) return 1 ;;
  esac
}

# Ids of the keys this machine uploaded (recognised by their title), except the one given.
host_own_ids() {  # host_own_ids <key list> [key to keep]
  printf '%s\n' "$1" | awk -F'\t' -v p="$(key_title_prefix)" -v k="${2:-}" \
    '{ split($3, a, " ") } index($2, p) == 1 && a[1] " " a[2] != k { print $1 }'
}

# githost_sync <name> [time limit]: makes the account hold the current login key and
# none of this machine's earlier ones.
githost_sync() {
  local key title existing id rc=0
  host_load "$1" || return 1
  HTTP_LIMIT=${2:-20}
  [ -s "$CUR/id_ed25519.pub" ] || return 1
  key=$(awk '{print $1 " " $2}' "$CUR/id_ed25519.pub")
  title="$(key_title_prefix)$(current_name)"
  existing=$(host_list) || return 1
  if ! printf '%s\n' "$existing" | awk -F'\t' -v k="$key" '{ split($3, a, " ") } a[1] " " a[2] == k { found = 1 } END { exit !found }'; then
    host_add "$title" "$key" "$(<"$CUR/expires")" || return 1
    log "$H_NAME: installed $title"
  fi
  for id in $(host_own_ids "$existing" "$key"); do
    host_delete "$id" || rc=1
  done
  [ "$rc" -ne 0 ] || rm -f "$ROOT/pending/$H_NAME"
  return "$rc"
}

# After a rotation: update every host, and remember the ones that could not be reached.
git_sync_all() {
  local name
  for name in $(git_hosts | cut -f1); do
    githost_sync "$name" "$1" 2>/dev/null ||
      { mkdir -p "$ROOT/pending"; : > "$ROOT/pending/$name"; log "$name: key upload failed, will retry"; }
  done
}

github_prepare() {  # prints the path of a gh CLI that may manage SSH keys
  local gh scopes
  # Exit codes 5, 3 and 4 tell a front end what is missing: the gh CLI, a login, the permission.
  gh=$(command -v gh) || die_code 5 "the GitHub CLI is needed for this: https://cli.github.com (then: gh auth login)"
  scopes=$("$gh" api -i user 2>/dev/null | tr -d '\r' | grep -i '^x-oauth-scopes:' || true)
  "$gh" api user --silent >/dev/null 2>&1 || die_code 3 "log in to GitHub first: gh auth login"
  case "$scopes" in
    *admin:public_key*|"") ;;   # no scope list: a fine-grained token; the upload is the test
    *)
      [ -t 0 ] && [ -t 1 ] ||
        die_code 4 "the gh CLI may not manage SSH keys yet. Run once: gh auth refresh -h github.com -s admin:public_key"
      {
        echo "GitHub has to let the gh CLI manage your SSH keys. This happens once:"
        echo "  1. gh shows a one-time code below. Press Enter HERE first; that opens the browser"
        echo "     and makes gh start waiting for you."
        echo "  2. Type the code into the page and approve."
        echo "  3. Come back to this terminal; it continues by itself."
        echo
      } >&2
      "$gh" auth refresh -h github.com -s admin:public_key >&2 || die "permission was not granted" ;;
  esac
  echo "$gh"
}

token_instructions() {
  case "$1" in
    gitlab) cat <<EOF
Create a personal access token with the 'api' scope:
  $2/-/user_settings/personal_access_tokens
GitLab has no narrower scope that may add SSH keys. Give the token an expiry date you are comfortable with.
EOF
      ;;
    forgejo|gitea) cat <<EOF
Create an access token whose only permission is 'user: read and write':
  $2/user/settings/applications
EOF
      ;;
    bitbucket) cat <<EOF
Create an API token "with scopes" for Bitbucket, with these four scopes:
  read:user:bitbucket  read:ssh-key:bitbucket  write:ssh-key:bitbucket  delete:ssh-key:bitbucket
  https://id.atlassian.com/manage-profile/security/api-tokens
EOF
      ;;
  esac
}

cmd_githost() {
  local kind=$1 action=${2:-status} url="" ssh_host="" name="" api="" ssh="" token err id uuid names host
  shift; [ $# -eq 0 ] || shift
  while [ $# -gt 0 ]; do
    case "$1" in
      --ssh-host) ssh_host=${2:?--ssh-host needs a host name}; shift ;;
      -*) die "$kind: unknown option '$1'" ;;
      *) url=${1%/} ;;
    esac
    shift
  done
  need_setup

  # Which host is meant. GitHub and Bitbucket are single services; the others have an address.
  case "$kind" in
    github)    name=github; api=-; ssh=github.com,gist.github.com,ssh.github.com ;;
    bitbucket) name=bitbucket.org; api=https://api.bitbucket.org; ssh=bitbucket.org,altssh.bitbucket.org ;;
    gitlab)    [ -n "$url" ] || [ "$action" != enable ] || url=https://gitlab.com ;;
  esac
  if [ -n "$url" ] && [ -z "$name" ]; then
    case "$url" in http://*|https://*) ;; *) url="https://$url" ;; esac
    case "$url" in *[!A-Za-z0-9._:/~-]*) die "that does not look like a server address: $url" ;; esac
    api=$url
    host=${url#*://}; host=${host%%/*}
    name=$(printf '%s' "$host" | tr ':' '_')
    ssh=${ssh_host:-${host%%:*}}
    [ "$name" != gitlab.com ] || ssh=gitlab.com,altssh.gitlab.com
  fi
  [ -z "$ssh_host" ] || ssh=$ssh_host

  case "$action" in
    enable)
      if [ "$kind" = github ]; then
        H_EXTRA=$(github_prepare) || exit $?
        host_save github github - "$ssh" "$H_EXTRA"
        [ "$GITHUB_SYNC" != yes ] || set_config GITHUB_SYNC no
      else
        [ -n "$name" ] || die "usage: ssh-rotate $kind enable <https://your-server> [--ssh-host <name used with ssh>]"
        have curl || die "curl is needed for this"
        json_tool >/dev/null || exit 1
        token=${SSH_ROTATE_TOKEN:-}
        if [ -z "$token" ]; then
          [ -t 0 ] || die "no terminal to ask for the access token; pass it in SSH_ROTATE_TOKEN"
          token_instructions "$kind" "$api" >&2
          printf 'Paste the token (it is not shown): ' >&2
          IFS= read -rs token; echo >&2
        fi
        case "$token" in ''|*[!A-Za-z0-9_.=+/~:-]*) die "that does not look like an access token" ;; esac
        token_put "$name" "$token"
        host_save "$name" "$kind" "$api" "$ssh" -
        host_load "$name"
        HTTP_LIMIT=30
        if [ "$kind" = bitbucket ]; then
          # Bitbucket addresses the account by its id, which the token can look up.
          uuid=$(host_http GET "$api/2.0/user" 2>/dev/null | json_field uuid || true)
          uuid=${uuid//\{/%7B}; uuid=${uuid//\}/%7D}
          [ -n "$uuid" ] || { token_del "$name"; host_forget "$name"; die "Bitbucket did not accept the token (it needs the read:user:bitbucket scope too)"; }
          host_save "$name" "$kind" "$api" "$ssh" "$uuid"
        fi
        if ! err=$(githost_check "$name"); then
          token_del "$name"; host_forget "$name"
          die "$name did not accept the token: ${err:-no answer}"
        fi
      fi
      cmd_ensure
      if ! githost_sync "$name" 30; then
        [ "$kind" = github ] || token_del "$name"
        host_forget "$name"
        die "could not upload the key to $name; nothing was enabled"
      fi
      write_ssh_config
      echo "$name now gets each new login key, and the previous one is deleted."
      echo "Check with: ssh -T git@${ssh%%,*}"
      ;;
    disable|sync|status)
      names=$(git_hosts | awk -F'\t' -v k="$kind" -v n="$name" '$2 == k && (n == "" || $1 == n) { print $1 }')
      if [ -z "$names" ]; then
        [ "$action" = status ] || die "$kind sync is not enabled${url:+ for $url}: ssh-rotate $kind enable"
        echo "$kind: not enabled"; return 0
      fi
      [ "$action" != sync ] || cmd_ensure
      for name in $names; do
        host_load "$name"; HTTP_LIMIT=30
        case "$action" in
          disable)
            for id in $(host_own_ids "$(host_list 2>/dev/null || true)"); do
              host_delete "$id" 2>/dev/null || note "could not delete key $id from $name"
            done
            [ "$kind" = github ] || token_del "$name"
            host_forget "$name"; rm -f "$ROOT/pending/$name"
            [ "$name" != github ] || [ "$GITHUB_SYNC" != yes ] || set_config GITHUB_SYNC no
            echo "$name: sync is off and this machine's rotating keys were deleted from your account." ;;
          sync)
            githost_sync "$name" 30 || die "$name: sync failed"
            echo "$name has the current login key." ;;
          status)
            echo "$name ($kind): enabled$([ ! -e "$ROOT/pending/$name" ] || echo ', an upload is pending')"
            host_list 2>/dev/null | awk -F'\t' -v p="$(key_title_prefix)" 'index($2, p) == 1 { print "  on the account: " $2 }' ||
              note "could not reach $name" ;;
        esac
      done
      [ "$action" != disable ] || write_ssh_config
      ;;
    *) die "usage: ssh-rotate $kind <enable|disable|sync|status> [server address]" ;;
  esac
}

# Runs the list call once and prints only what went wrong.
githost_check() {
  host_load "$1" || return 1
  { host_list >/dev/null; } 2>&1
}

# ---------------------------------------------------------------------------
# Audit and recovery. Rotation only means something once no permanent key still gets in,
# and removing those is only safe with another way back in if this machine is lost.
# ---------------------------------------------------------------------------

sh_audit() { cat <<'EOF'
set -eu
# Under Windows' own sshd this would be Git's sh, started by cmd.exe. The keys of a Windows
# account are not where this script would look, so it hands over to the PowerShell version.
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) if [ -n "${PROMPT:-}" ]; then echo WINDOWS; exit 3; fi ;; esac
me=$(id -un)
for f in "$HOME/.ssh/authorized_keys" "$HOME/.ssh/authorized_keys2" "/etc/ssh/authorized_keys.d/$me"; do
  [ -r "$f" ] || continue
  grep -v '^[[:space:]]*#' "$f" | grep -v '^[[:space:]]*$' | while IFS= read -r line; do
    printf '%s\t%s\n' "$f" "$line"
  done
done
echo END
EOF
}

sh_addkey() { cat <<'EOF'
set -eu
umask 077
# Under Windows' own sshd this would be Git's sh, started by cmd.exe. The keys of a Windows
# account are not where this script would look, so it hands over to the PowerShell version.
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) if [ -n "${PROMPT:-}" ]; then echo WINDOWS; exit 3; fi ;; esac
mkdir -p "$HOME/.ssh"
f="$HOME/.ssh/authorized_keys"
[ -e "$f" ] || : > "$f"
if grep -qF "$B64" "$f"; then echo ALREADY
else
  [ -z "$(tail -c1 "$f")" ] || echo >> "$f"
  printf '%s\n' "$LINE" >> "$f"
  echo ADDED
fi
EOF
}

# Turns the lines of sh_audit into: file <tab> type <tab> key <tab> comment <tab> ca(0|1)
parse_keys() {
  awk -F'\t' '$1 != "END" {
    n = split($2, w, " ")
    for (i = 1; i < n; i++) if (w[i] ~ /^(ssh-|ecdsa-|sk-)/ && w[i + 1] ~ /^AAAA[A-Za-z0-9+\/=]+$/) {
      comment = ""
      for (j = i + 2; j <= n; j++) comment = comment (j > i + 2 ? " " : "") w[j]
      ca = index($2, "cert-authority")
      printf "%s\t%s\t%s\t%s\t%d\n", $1, w[i], w[i + 1], (comment == "" ? "-" : comment), (ca > 0 && ca < index($2, w[i]))
      next
    }
  }'
}

# Prints "key <tab> file" for every public key file in ~/.ssh: the keys known to be yours.
local_pubs() {
  local f
  for f in "${SSH_ROTATE_KEYS_DIR:-$HOME/.ssh}"/*.pub; do
    [ -f "$f" ] || continue
    awk -v f="$f" '$2 ~ /^AAAA/ { print $2 "\t" f; exit }' "$f"
  done
}

cmd_audit() {
  need_setup
  local porcelain=no
  [ "${1:-}" != --porcelain ] || { porcelain=yes; shift; }
  cmd_ensure
  local target raw ours recovery="" pubs rc=0 mine_total=0 other_total=0
  local file type key comment is_ca fp mine name others
  ours=$(awk '{print $2}' "$CA_PUB")
  [ ! -f "$RECOVERY_PUB" ] || recovery=$(awk '{print $2}' "$RECOVERY_PUB")
  pubs=$(local_pubs)
  while IFS= read -r target; do
    [ -n "$target" ] || continue
    raw=$(sh_audit | ssh_ -o BatchMode=yes "${CONNECT[@]}" -o IdentitiesOnly=yes -i "$CUR/id_ed25519" \
      -o "$(algo_keyword)=ssh-ed25519-cert-v01@openssh.com" "$target" ": && sh -s" 2>/dev/null) || true
    if [ "$raw" = WINDOWS ] || { [ -z "$raw" ] && verify_cert_login "$target" </dev/null; }; then
      # The certificate works, but this is not a Unix shell: a Windows server.
      if [ "$porcelain" = yes ]; then printf 'host\t%s\tok\n' "$target"
      else printf '%s\n  a Windows server; its other keys cannot be listed from here\n' "$target"; fi
      continue
    fi
    if ! contains "$raw" END; then
      if [ "$porcelain" = yes ]; then printf 'host\t%s\tunreachable\n' "$target"
      else printf '%s\n  could not be reached with your certificate\n' "$target"; fi
      rc=1; continue
    fi
    if [ "$porcelain" = yes ]; then printf 'host\t%s\tok\n' "$target"; else echo "$target"; fi
    while IFS="$TAB" read -r file type key comment is_ca; do
      [ -n "$key" ] || continue
      [ "$key" != "$ours" ] || continue
      [ "$comment" != - ] || comment=""
      fp=$(printf '%s %s\n' "$type" "$key" | ssh-keygen -lf - 2>/dev/null | awk '{print $2}')
      mine=$(printf '%s\n' "$pubs" | awk -F'\t' -v k="$key" '$1 == k { print $2; exit }')
      if [ "$key" = "$recovery" ]; then
        if [ "$porcelain" = yes ]; then printf 'key\t%s\trecovery\t%s\t%s\t-\n' "$target" "$fp" "$comment"
        else echo "  your recovery key is installed"; fi
      elif [ "$is_ca" = 1 ]; then
        if [ "$porcelain" = yes ]; then printf 'key\t%s\tother-ca\t%s\t%s\t-\n' "$target" "$fp" "$comment"
        else echo "  also trusts another certificate authority: $fp ${comment:-(no name)}"; fi
      elif [ -n "$mine" ]; then
        mine_total=$((mine_total + 1)); rc=1
        if [ "$porcelain" = yes ]; then printf 'key\t%s\tpermanent\t%s\t%s\t%s\n' "$target" "$fp" "$comment" "$mine"
        else
          echo "  STILL ACCEPTS your permanent key $fp ${comment:-(no name)}"
          echo "      it is $mine; remove it with: ssh-rotate retire $target $mine"
        fi
      else
        other_total=$((other_total + 1))
        if [ "$porcelain" = yes ]; then printf 'key\t%s\tpermanent\t%s\t%s\t-\n' "$target" "$fp" "$comment"
        else echo "  also accepts a permanent key that is not one of your key files: $fp ${comment:-(no name)}"; fi
      fi
    done <<EOF
$(printf '%s\n' "$raw" | parse_keys)
EOF
  done <<EOF
$(targets "$@")
EOF
  # Accounts on Git hosts: keys that are there besides the rotating one.
  if [ $# -eq 0 ]; then
    for name in $(git_hosts | cut -f1); do
      host_load "$name" || continue
      HTTP_LIMIT=20
      others=$(host_list 2>/dev/null | awk -F'\t' -v p="$(key_title_prefix)" 'index($2, p) != 1 { print $2 }' | paste -sd, - || true)
      [ -n "$others" ] || continue
      rc=1
      if [ "$porcelain" = yes ]; then printf 'account\t%s\t%s\n' "$name" "$others"
      else printf '%s\n  the account also holds permanent keys: %s\n' "$name" "$others"; fi
    done
  fi
  if [ "$porcelain" = no ]; then
    echo
    if [ "$mine_total" -gt 0 ]; then
      echo "$mine_total permanent key(s) of yours still work. Until they are retired, a copy of that"
      echo "key file gets in no matter how often the rotating key changes."
    elif [ "$rc" -eq 0 ]; then
      echo "Nothing permanent of yours gets in: the rotating key is your only way in."
    fi
    [ "$other_total" -eq 0 ] ||
      echo "$other_total key(s) that are not yours were listed for information; check they belong to people you expect."
    [ -n "$recovery" ] ||
      echo "You have no recovery key. Before retiring your last permanent key, make one: ssh-rotate recovery create"
  fi
  return "$rc"
}

recovery_install() {  # recovery_install <target>
  local out line b64
  line="$(awk '{print $1, $2}' "$RECOVERY_PUB") ssh-rotate-recovery@$(short_host)"
  b64=$(awk '{print $2}' "$RECOVERY_PUB")
  out=$(remote_run "$1" "LINE='$line' B64='$b64'" "$(sh_addkey)" "'UNSUPPORTED'" 2>/dev/null) || out=FAILED
  case "$out" in
    ADDED) echo "$1: recovery key installed" ;;
    ALREADY) echo "$1: recovery key was already there" ;;
    UNSUPPORTED) echo "$1: Windows server; add the recovery key there yourself" >&2; return 1 ;;
    *) echo "$1: could not install the recovery key" >&2; return 1 ;;
  esac
}

cmd_recovery() {
  need_setup
  local file target ps out b64 rc=0 path=""
  [ ! -r "$ROOT/recovery.path" ] || path=$(<"$ROOT/recovery.path")
  case "${1:-status}" in
    create)
      file=${2:-$HOME/ssh-rotate-recovery-key}
      [ ! -f "$RECOVERY_PUB" ] ||
        die "there already is a recovery key (ssh-rotate recovery status). Remove it first: ssh-rotate recovery remove"
      [ ! -e "$file" ] || die "$file already exists"
      note "choose a strong password for the recovery key. Using it takes both the file and the password."
      keygen_ask -q -t ed25519 -C "ssh-rotate-recovery@$(short_host)" -f "$file" ||
        { rm -f "$file" "$file.pub"; die "could not create the recovery key"; }
      if ! encrypted "$file"; then
        rm -f "$file" "$file.pub"
        die "the recovery key must have a password: without one it is just another permanent key lying around"
      fi
      mv -f "$file.pub" "$RECOVERY_PUB"
      echo "$file" > "$ROOT/recovery.path"
      log "created recovery key $(fingerprint "$RECOVERY_PUB")"
      while IFS= read -r target; do
        [ -n "$target" ] || continue
        recovery_install "$target" </dev/null || rc=1
      done <<EOF
$(targets)
EOF
      echo
      echo "Recovery key: $file"
      echo "Move that file off this machine now: into a password manager, or onto a USB stick kept elsewhere."
      echo "If this machine is ever lost, it gets you back in from any other one:"
      echo "    ssh -o IdentitiesOnly=yes -i <the file> user@server"
      return "$rc" ;;
    remove)
      [ -f "$RECOVERY_PUB" ] || die "there is no recovery key"
      b64=$(awk '{print $2}' "$RECOVERY_PUB")
      ps=$(ps_remove); ps=${ps//__KEYS__/$b64}; ps=${ps//__SUFFIX__/before-ssh-rotate-recovery}; ps=${ps//__GUARD__/1}
      while IFS= read -r target; do
        [ -n "$target" ] || continue
        if out=$(remote_run "$target" "KEYS='$b64' SUFFIX=before-ssh-rotate-recovery GUARD=1" "$(sh_remove)" "$ps" </dev/null 2>/dev/null) &&
           [ "$out" != LASTKEY ]; then
          echo "$target: recovery key removed"
        else
          echo "$target: recovery key NOT removed" >&2; rc=1
        fi
      done <<EOF
$(targets)
EOF
      if [ "$rc" -eq 0 ]; then
        rm -f "$RECOVERY_PUB" "$ROOT/recovery.path"
        echo "The recovery key is no longer accepted anywhere. Delete the key file wherever you kept it."
      fi
      return "$rc" ;;
    status)
      if [ ! -f "$RECOVERY_PUB" ]; then
        echo "No recovery key. If this machine is lost, servers that only trust its CA are out of reach."
        echo "Make one with: ssh-rotate recovery create"
      else
        echo "Recovery key: $(fingerprint "$RECOVERY_PUB")"
        if [ -n "$path" ] && [ -e "$path" ]; then
          echo "WARNING: its file is still on this machine at $path. Move it somewhere else."
        else
          echo "Its file is no longer where it was created, so it has been moved away."
        fi
      fi ;;
    *) die "usage: ssh-rotate recovery <create [file]|status|remove>" ;;
  esac
}

# ---------------------------------------------------------------------------
# Status and checks
# ---------------------------------------------------------------------------

# The same facts as 'status', one name=value per line, for programs. Names are stable.
status_porcelain() {
  local line name
  echo "version=$VERSION"
  echo "secure_enclave_available=$(secure_enclave_available && echo yes || echo no)"
  if [ ! -f "$CA_PUB" ]; then echo "setup=no"; return 0; fi
  echo "setup=yes"
  echo "backend=$CA_BACKEND"
  echo "touch_id=$CA_TOUCH_ID"
  echo "ca_fingerprint=$(fingerprint "$CA_PUB")"
  if [ -r "$CUR/created" ] && [ -r "$CUR/expires" ]; then
    echo "key_fingerprint=$(fingerprint "$CUR/id_ed25519.pub")"
    echo "key_created=$(<"$CUR/created")"
    echo "key_expires=$(<"$CUR/expires")"
  fi
  echo "rotate_minutes=$ROTATE_MINUTES"
  echo "rotate_hours=$((ROTATE_MINUTES / 60))"
  echo "principal=$PRINCIPAL"
  echo "allowed_from=$ALLOWED_FROM"
  echo "background=$(bg_state || true)"
  if [ ! -f "$RECOVERY_PUB" ]; then echo "recovery=none"
  elif [ -r "$ROOT/recovery.path" ] && [ -e "$(<"$ROOT/recovery.path")" ]; then echo "recovery=on-disk"
  else echo "recovery=yes"; fi
  if [ -s "$HOSTS" ]; then while IFS= read -r line; do [ -z "$line" ] || echo "host=$line"; done < "$HOSTS"; fi
  # git_host=<name> <kind> <api address or -> <pending: yes|no>, tab-separated
  git_hosts | while IFS="$TAB" read -r name kind api _ _; do
    printf 'git_host=%s\t%s\t%s\t%s\n' "$name" "$kind" "$api" "$([ -e "$ROOT/pending/$name" ] && echo yes || echo no)"
  done
}

cmd_status() {
  local now bg due
  [ "${1:-}" != --porcelain ] || { status_porcelain; return 0; }
  now=$(date +%s)
  if [ -f "$CA_PUB" ]; then
    echo "CA key:        $(fingerprint "$CA_PUB")"
    echo "Kept in:       $(backend_name)"
    if [ "$CA_BACKEND" = secure-enclave ]; then
      sc_auth list-ctk-identities 2>/dev/null |
        awk -v l="$CA_LABEL" '$4 == l { print "CA identity:   valid=" $NF ", identity certificate until " $(NF-2), $(NF-1) }'
    fi
  else
    echo "CA key:        not set up (run 'ssh-rotate setup')"
  fi
  if [ -r "$CUR/created" ]; then
    echo "Login key:     $(fingerprint "$CUR/id_ed25519.pub")"
    if [ "$(<"$CUR/expires")" -gt "$now" ]; then
      echo "               created $(( (now - $(<"$CUR/created")) / 60 )) min ago, certificate expires in $(( ($(<"$CUR/expires") - now) / 60 )) min"
    else
      echo "               certificate expired $(( (now - $(<"$CUR/expires")) / 60 )) min ago; the next ssh makes a new one"
    fi
  else
    echo "Login key:     none yet"
  fi
  echo "Rotation:      every $(period_words "$ROTATE_MINUTES"), principal $PRINCIPAL"
  if [ -r "$CUR/created" ]; then
    due=$(( $(<"$CUR/created") + ROTATE_MINUTES * 60 - now ))
    if [ "$due" -gt 0 ]; then echo "Next key:      due in $((due / 60)) min, made at the first connection after that"
    else echo "Next key:      due now, made at your next connection"; fi
  fi
  echo "Accepted from: ${ALLOWED_FROM:-anywhere}"
  if [ ! -f "$RECOVERY_PUB" ]; then echo "Recovery key:  none (ssh-rotate recovery create)"
  else echo "Recovery key:  $(fingerprint "$RECOVERY_PUB")"; fi
  echo "Hosts:         $( [ -s "$HOSTS" ] && paste -sd' ' "$HOSTS" || echo none )"
  [ -z "$(git_hosts)" ] || echo "Git hosts:     $(git_hosts | cut -f1 | paste -sd' ' -) (each new key is uploaded to your account)"
  if bg=$(bg_state); then echo "Background:    $bg"
  else echo "Background:    no job (keys still rotate on demand when you ssh)"; fi
}

cmd_doctor() {
  local bad=0 first inc
  ok()   { echo "ok    $*"; }
  warn() { echo "note  $*"; }
  fail() { echo "FAIL  $*"; bad=1; }
  if version_at_least "$(ssh_version)" 8 2; then ok "OpenSSH client $(ssh_version | tr ' ' '.')"
  else fail "OpenSSH client is older than 8.2: $(ssh -V 2>&1)"; fi
  if [ -f "$CA_PUB" ]; then ok "CA $(fingerprint "$CA_PUB") in $(backend_name)"
  else fail "no CA yet: run 'ssh-rotate setup'"; echo; return 1; fi
  case "$CA_BACKEND" in
    secure-enclave)
      if se_identity_fp >/dev/null; then ok "Secure Enclave identity '$CA_LABEL' exists"
      else fail "Secure Enclave identity '$CA_LABEL' is missing; the CA can no longer sign"; fi ;;
    agent)
      if contains "$(ssh-add -L 2>/dev/null || true)" "$(awk '{print $2}' "$CA_PUB")"; then ok "CA key is loaded in the ssh-agent"
      else fail "CA key is not loaded in the ssh-agent (ssh-add it)"; fi ;;
    file|fido|password)
      if [ -f "$CA_KEY" ]; then ok "CA key file present"; else fail "CA key file $CA_KEY is missing"; fi
      [ "$CA_BACKEND" != file ] || warn "the CA key is an unprotected file: whoever can read your home folder can sign their own keys" ;;
  esac
  if [ -x "$SELF" ]; then ok "tool installed at $SELF"; else fail "$SELF is missing or not executable"; fi
  inc=$(include_line)
  first=$(grep -v '^[[:space:]]*\(#.*\)\{0,1\}$' "$SSH_CONFIG" 2>/dev/null | head -n1 || true)
  if [ "$first" = "$inc" ]; then ok "$SSH_CONFIG loads the rotating key first"
  elif grep -qxF "$inc" "$SSH_CONFIG" 2>/dev/null; then fail "'$inc' is not the first line of $SSH_CONFIG, so other keys may be offered first"
  else fail "$SSH_CONFIG does not include $ROOT/ssh_config (run 'ssh-rotate setup')"; fi
  if is_fresh; then ok "login key is current"
  elif unattended; then fail "login key is stale although it can rotate unattended (see $LOG)"
  else ok "login key is due; the next ssh will ask you to confirm a new one"; fi
  if bg_state >/dev/null; then ok "background job: $(bg_state)"
  else warn "no background job; keys still rotate on demand when you ssh"; fi
  if have ssh-rotate; then ok "'ssh-rotate' is on your PATH"; else warn "'ssh-rotate' is not on your PATH (use $SELF)"; fi
  if [ ! -f "$RECOVERY_PUB" ]; then warn "no recovery key: if this machine is lost you need another way in (ssh-rotate recovery create)"
  elif [ -r "$ROOT/recovery.path" ] && [ -e "$(<"$ROOT/recovery.path")" ]; then warn "the recovery key file is still on this machine: move $(<"$ROOT/recovery.path") somewhere else"
  else ok "recovery key exists and its file is not on this machine"; fi
  if [ -s "$HOSTS" ]; then ok "$(wc -l < "$HOSTS" | tr -d ' ') host(s) enrolled; 'ssh-rotate audit' shows what else still gets in"
  else warn "no hosts yet: ssh-rotate add user@your-server"; fi
  local name
  for name in $(git_hosts | cut -f1); do
    if [ -e "$ROOT/pending/$name" ]; then fail "$name: a key upload is pending; the next ssh to it retries"
    else ok "$name gets each new login key"; fi
  done
  return $bad
}

usage() { cat <<EOF
ssh-rotate $VERSION: SSH login keys that replace themselves

Getting started
  setup [options]           create the CA and the first login key, hook into ssh, start the background job
      --backend B           what guards the CA key: secure-enclave, fido (security key), password,
                            agent or file (default: Secure Enclave on a Mac that has one, else password)
      --touch-id            Secure Enclave: require Touch ID for every rotation
      --every PERIOD        replace the login key this often: 30m, 1h, 12h, 2d (default 1d)
      --from ADDRS          servers accept your certificates only from these addresses (comma-separated)
  add <[user@]host>...      make a server trust your CA, then verify certificate login
  status [--porcelain]      show the CA, the current login key and the enrolled hosts
  doctor                    check the local installation

Servers
  list                      enrolled hosts
  test [host...]            check certificate login on some or all enrolled hosts
  audit [host...]           list every other key that still gets in to your servers and Git accounts
  retire <host> <key.pub>.. remove old static keys from a server once certificates work
  remove [--force] <host>.. remove the CA from a server (kill switch for one server)
  forget <host>...          stop using the rotating key for a host without touching it
  sync                      push the current CA line to every host again (after 'set')
  snippet <kind> [account]  print the trust in another form: line, shell, nixos, cloud-init,
                            ansible, sshd (whole server), windows

Keys
  recovery <create [file]|status|remove>
                            a password-protected spare key, kept off this machine, for when it is lost
  rotate                    replace the login key now
  set every <period>        how often the login key is replaced: 30m, 1h, 12h, 2d (10 minutes at least)
  set <name> <value>        overlap (minutes), allowed-from (addresses or 'any'), principal, cert-options

Git hosts (your account there gets each new login key, the previous one is deleted)
  github    <enable|disable|sync|status>
  gitlab    <enable|disable|sync|status> [https://your-gitlab]     default: gitlab.com
  bitbucket <enable|disable|sync|status>
  forgejo   <enable|disable|sync|status> <https://your-forgejo>    also Codeberg
  gitea     <enable|disable|sync|status> <https://your-gitea>
      --ssh-host NAME       the name you use with ssh/git, when it differs from the web address

Maintenance
  upgrade                   download the latest version
  uninstall                 remove the ssh hook, the background job and the command link
  version

  background on|off         the half-hourly check that renews a due key, or tells you it needs you

Used by ssh and the background check: ensure, background.
EOF
}

case "${1:-}" in
  setup|init)        shift; cmd_setup "$@" ;;
  status)            shift; cmd_status "$@" ;;
  doctor)            cmd_doctor ;;
  add|enroll)        shift; cmd_add "$@" ;;
  remove|unenroll)   shift; cmd_remove "$@" ;;
  forget)            shift; cmd_forget "$@" ;;
  retire)            shift; cmd_retire "$@" ;;
  list|hosts)        cmd_list ;;
  test)              shift; cmd_test "$@" ;;
  audit)             shift; cmd_audit "$@" ;;
  recovery)          shift; cmd_recovery "$@" ;;
  sync)              cmd_sync ;;
  snippet)           shift; cmd_snippet "$@" ;;
  ca-line)           ca_line ;;
  rotate)            cmd_rotate; cmd_status ;;
  ensure)            shift; cmd_ensure "$@" ;;
  background)        shift; cmd_background "$@" ;;
  set)               shift; cmd_set "$@" ;;
  github|gitlab|bitbucket|forgejo|gitea) cmd_githost "$@" ;;
  upgrade)           cmd_upgrade ;;
  uninstall)         cmd_uninstall ;;
  version|--version|-V) echo "ssh-rotate $VERSION" ;;
  help|--help|-h)    usage ;;
  *)                 usage >&2; exit 2 ;;
esac
